ASP.NET CORE 2.1 with knockout js 我没有收到模型中的数据?

ASP.NET CORE 2.1 with knockout js I don't receive the data in the model?

我是 ASP.NET CORE 的新手,我正在从 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 代码,

//模型 功能性别模型(){ 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();

}

// 视图模型 功能性别视图模型(){ var genderViewModel = this;

//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.NET MVC5 中使用相同的代码,但我正在迁移到 ASP.NET CORE,但我遇到了这个问题,我感谢您的帮助

我最好的猜测是您的服务器需要 form 有效载荷,而您的 javascript 客户端发送 JSON.

的有效载荷

由于你的js发送了一个JSON,如果你的controller没有[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 Core 中用 [ApiController] 注释的控制器与普通控制器不同。如果您的控制器有一个 [ApiController],默认情况下操作方法需要一个 JSON 的主体。否则,它需要一个表单。