knockout.js ASP.NET CORE 2.1用knockout js我在模型里收不到数据吗?

mftmpeh8  于 2022-11-10  发布在  .NET
关注(0)|答案(1)|浏览(140)

我是ASP .NETCORE的新手,我正在从knockout js发送绑定数据,但在我的控制器中没有接收到它,如下图所示,

我不知道为什么我没有得到我通过knockout js发送的模型,一开始我遇到了一个问题,因为JSON格式的数据输出是camelCase,但我使用以下命令将其添加到STARTUP中,解决了这个问题,

services.AddMvc (). AddJsonOptions ( options =>
                 options.SerializerSettings.ContractResolver = new DefaultContractResolver ()
             );

实现该命令已经在PascalCase中提供了数据的输出,但是我有一个带有bindadas属性的窗体,它没有向控制器发送数据,这是我的窗体的代码,

<div id="divCreateGenders" data-bind="visible: IsNew">
    <form id="FormCreateGenders" method="post">
        <div class="form-horizontal" data-bind="with: GenderModel">
            <h3><strong>Crear Nuevo</strong></h3>
            <br />
            <div class="form-group">
                <label class="control-label col-md-2"><strong>Codigo:</strong></label>
                <div class="col-md-4">
                    <input id="TextboxGenderId" name="TextboxGenderId" type="text" class="form-control" data-bind="value: GenderId" maxlength="1" placeholder="Por ejemplo, I" required />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-2"><strong>Genero:</strong></label>
                <div class="col-md-4">
                    <input id="TextboxGenderName" name="TextboxGenderName" type="text" class="form-control" data-bind="value: GenderName" maxlength="15" placeholder="Introduzca un genero..." required />
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <button class="btn btn-success" data-bind="click: $parent.Create">Crear</button>
                </div>
            </div>
        </div>
    </form>
</div>

这是我的JavaScript代码
//模型函数genderModel(){ var genderModel = this;

genderModel.GenderId = ko.observable();
genderModel.GenderName = ko.observable();
genderModel.CreateBy = ko.observable();
genderModel.CreationDate = ko.observable();
genderModel.ModifiedBy = ko.observable();
genderModel.ModifiedDate = ko.observable();

}
// ViewModel函数的参数设置

//Variables publicas//

genderViewModel.GenderModel = ko.observable(new genderModel());
genderViewModel.Genders = ko.observableArray();
genderViewModel.IsNew = ko.observable(false);
genderViewModel.IsBackToListButton = ko.observable(false);
genderViewModel.IsEdit = ko.observable(false);
genderViewModel.IsNewButton = ko.observable(true);
genderViewModel.IsDetails = ko.observable(false);
genderViewModel.ShowResult = ko.observable(true);
//Metodos Publicos//

genderViewModel.New = function () {
    genderViewModel.IsNew(true);
    genderViewModel.IsBackToListButton(true);
    genderViewModel.IsNewButton(false);
    genderViewModel.IsEdit(false);
    genderViewModel.IsDetails(false);
    genderViewModel.ShowResult(false);
    genderViewModel.Genders.removeAll();
    genderViewModel.GenderModel().GenderId(undefined);
    genderViewModel.GenderModel().GenderName(undefined);
    genderViewModel.GenderModel().CreateBy(undefined);
    genderViewModel.GenderModel().CreationDate(undefined);
    genderViewModel.GenderModel().ModifiedBy(undefined);
    genderViewModel.GenderModel().ModifiedDate(undefined);
    $('#TextboxGenderId').focus();

};

genderViewModel.Delete = function (model) {
    swal({
        title: "Esta seguro?",
        text: "Que desea eliminar este genero?",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn-danger",
        confirmButtonText: "Si",
        cancelButtonText: "Cancelar",
        closeOnConfirm: false,
        closeOnCancel: false
    },
        function (isConfirm) {
            if (isConfirm) {
                $.ajax({
                    url: '/AdminGenders/Delete',
                    data: ko.toJSON(model),
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    async: true,
                    success: function (data) {
                        if (data.Success) {
                            genderViewModel.LoadAll();
                            swal("Eliminado!", "Se ha elimanado el genero satisfactoriamente", "success");
                        }
                        else {
                            swal("Error eliminando el genero!", data.Data, "error")
                        }
                    }
                });

            } else {
                swal("Cancelado!", "El genero no ha sido elimanado", "error");
            }
        });
};

genderViewModel.Details = function (model) {
    genderViewModel.IsNew(false);
    genderViewModel.IsNewButton(false);
    genderViewModel.IsBackToListButton(true);
    genderViewModel.IsDetails(true);
    genderViewModel.ShowResult(false);
    genderViewModel.GenderModel().GenderId(model.GenderId);
    genderViewModel.GenderModel().GenderName(model.GenderName);
    genderViewModel.GenderModel().CreateBy(model.CreateBy);
    genderViewModel.GenderModel().CreationDate(model.CreationDate);
    genderViewModel.GenderModel().ModifiedBy(model.ModifiedBy);
    genderViewModel.GenderModel().ModifiedDate(model.ModifiedDate);

    $.ajax({
        url: '/AdminGenders/Detail',
        data: ko.toJSON(model),
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        async: true,
        success: function (data) {
            if (data.Success) {
            }
            else {
                alert(data.Data);
            }
        },
        error: function (ex) {
            swal("Error mostrando el genero!", "Ha ocurrido un error mientras se mostrando el genero!", "error")
        }
    });

};

genderViewModel.Edit = function (model) {
    genderViewModel.IsNewButton(false);
    genderViewModel.IsBackToListButton(true);
    genderViewModel.ShowResult(false);
    genderViewModel.IsDetails(false);
    genderViewModel.IsNew(false);
    genderViewModel.IsEdit(true);
    genderViewModel.GenderModel().GenderId(model.GenderId);
    genderViewModel.GenderModel().GenderName(model.GenderName);
    genderViewModel.GenderModel().CreateBy(model.CreateBy);
    genderViewModel.GenderModel().CreationDate(model.CreationDate);
    genderViewModel.GenderModel().ModifiedBy(model.ModifiedBy);
    genderViewModel.GenderModel().ModifiedDate(model.ModifiedDate);
    $('#TextboxGenderId').focus();
};

genderViewModel.Create = function () {
    if (genderViewModel.IsNew()) {
        $.ajax({
            url: '/AdminGenders/Create',
            data: ko.toJSON(genderViewModel.GenderModel()),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            async: true,
            success: function (data) {
                if (data.Success) {
                    $('#TextboxGenderId').val('');
                    $('#TextboxGenderName').val('');
                    $('#TextboxGenderId').focus();
                    swal("Genero creado!", "Se ha registrado correctamente!", "success")
                }
                else {
                    swal("Error creando el genero!", data.Data, "error")
                }
            },
            error: function (ex) {
                alert('Ocurrión un error');
            }
        });
    }
};

genderViewModel.Update = function (model) {
    if (genderViewModel.IsEdit()) {
        $.ajax({
            url: '/AdminGenders/Update',
            data: ko.toJSON(model),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            async: true,
            success: function (data) {
                if (data.Success) {
                    genderViewModel.BackToList();
                    swal("Genero actualizado!", "Se ha modificado correctamente!", "success")
                }
                else {
                    swal("Error actualizando el genero!", data.Data, "error")
                }
            },
            error: function (ex) {
                alert('Ocurrión un error');
            }
        });
    }
};

genderViewModel.BackToList = function () {
    genderViewModel.IsNew(false);
    genderViewModel.IsBackToListButton(false);
    genderViewModel.IsEdit(false);
    genderViewModel.IsDetails(false);
    genderViewModel.IsNewButton(true);
    genderViewModel.ShowResult(true);
    genderViewModel.LoadAll();

};

genderViewModel.LoadAll = function () {
    LoadListGenders();
};

// Metodos Privados //
var LoadListGenders = function () {
    $.ajax({
        url: '/AdminGenders/GetGender',
        data: null,
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        async: true,
        success: function (data) {
            if (data.Success) {
                genderViewModel.Genders.removeAll();
                genderViewModel.Genders(data.Data);
            }
            else {
                alert(data.Data);
            }
        },
        error: function (ex) {
            alert('Ocurrión un error, cargando los generos.');
        }
    });

};

}

jQuery(function () {
    var genderViewModel = new GenderViewModel();
    genderViewModel.LoadAll();
    ko.applyBindings(genderViewModel);
});

我不知道为什么它不工作,因为我有相同的代码在ASP.NETMVC5工作,但我迁移到ASP .NETCORE,我有这个问题,我会感谢帮助

juzqafwq

juzqafwq1#

我最好的猜测是,服务器需要form有效负载,而javascript客户端发送的有效负载为JSON
由于js发送的是JSON,如果控制器没有[ApiController]属性,请添加一个[FromBody]属性,这样modelbinder就可以知道绑定源:

// suppose your controller is not an ApiController
public async Task<JsonResult> Create(**[FromBody]**Gender gender)
{
    if(ModelState.IsValid){
        // ... model binding succeds
    }
    else{
        // ... 
    }
}

或者,如果您的控制器是ApiController,则使用[ApiController]


**[ApiController]**

[Route("/AdminGenders")]
public class AdminGendersController : ControllerBase
{
    public async Task<JsonResult> Create(Gender gender)
    {
        ...
    }
}

请注意,在ASP.NET核心中,使用[ApiController]注解的控制器与普通控制器不同。如果您的控制器具有[ApiController],则操作方法默认情况下需要JSON主体。否则,它需要表单。

相关问题