在制作Jquery / Ajax调用.net核心时,模型属性为null

问题描述 投票:2回答:2

在.net核心中进行jquery / ajax调用时,模型属性始终为null。知道这里有什么问题

var fileType = {
    fileTypeDescription: fileTypeDescription,
    isActive: isActive,
    sortOrder: sortOrder,
    CreatedDate: null,
    CreatedBy: null,
    ModifiedDate: null,
    ModifiedBy: null
};            

$.ajax({
    url: url,
    data: { a: fileType },
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        alert('Success');
    },
    error: function (data, status, jqXHR) {
    }
});

模型:

public class MdtFebFileType
{
    public int FileTypeId { get; set; }
    public string FileTypeDescription { get; set; }
    public bool IsActive { get; set; }
    public DateTime? CreatedDate { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? ModifiedDate { get; set; }
    public string ModifiedBy { get; set; }
    public int? SortOrder { get; set; }

}

方法:

[HttpPost]
public Response AddFileType(MdtFebFileType fileType)
{}

对于ajax调用中的数据部分,我也尝试了以下内容,但它们都没有工作。

JSON.stringify({ model: fileType })
JSON.stringify(fileType)
JSON.stringify({ 'model': fileType })
jquery ajax asp.net-core asp.net-core-mvc
2个回答
1
投票

知道这里有什么问题

模型数据没有以正确的格式发送,因此它与控制器操作的预期模型不匹配。

有两件事要解决这个问题。

首先按照客户端对模型进行字符串化,以便以正确的格式发送数据

data: JSON.stringify(fileType),

第二,您需要明确告诉操作在哪里查找模型,以便模型绑定器可以填充模型。

[FromBody]:使用配置的格式化程序绑定请求正文中的数据。根据请求的内容类型选择格式化程序。

[HttpPost]
public IActionResult AddFileType([FromBody]MdtFebFileType fileType) {
    //...
}

参考Model Binding in ASP.NET Core


0
投票

使用$ .post而不是$ .ajax。这解决了我的问题。

$.post(url, { fileTypeName: fileType })
                        .done(function (response, status, jqxhr) {

                        })
                        .fail(function (jqxhr, status, error) {

                        })
© www.soinside.com 2019 - 2024. All rights reserved.