我有这段代码会在点击时触发。当我在SaveNewProduct处设置断点时,所有值均为null。我尝试创建一个输入对象,尝试手动添加每个属性,但没有任何效果。请问我有什么提示或建议。

var input = {
    name: name,
    type: type,
    description: description,
    category: category,
    file: file.files[0],
    acronym: acronym
};

$.ajax({
    type: "POST",
    url: '/Admin/SaveNewProduct',

    processData: false,
    data: {
        name: name,
        type: type,
        description: description,
        category: category,
        file: file.files[0],
        acronym: acronym,
        input: input
    },
    success: function (response) {
        alert("saved okay");
    }
});

[HttpPost]
public async Task<ActionResult> SaveNewProduct(SaveNewProductInput input)
{
    ...
    //breakpoint here, input values are all null
    ...
}


SaveNewProductInput.cs

public class SaveNewProductInput
{
    public string Name { get; set; }
    public string Acronym { get; set; }
    public string Type { get; set; }
    public string Category { get; set; }
    public string Description { get; set; }
    public HttpPostedFileBase File { get; set; }
}


我也尝试删除processData,出现此错误Uncaught TypeError: Illegal invocation

最佳答案

您需要使用FormData在请求中发送文件,且processData并且contentType设置为false

var formData = new FormData();
formData.append("name", name);
formData.append("type", type);
formData.append("description", description);
formData.append("category", category);
formData.append("file", file.files[0]);
formData.append("acronym", acronym);

$.ajax({
    url: "/Admin/SaveNewProduct",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
        alert("saved okay");
    }
});

10-08 17:45