javascript - 对于 Controller 的 Ajax Post 方法,参数作为空值传入

标签 javascript c# asp.net-mvc

我有这段代码在点击时触发。当我在 SaveNewProduct 处设置断点时,所有值都为空。我试图创建一个输入对象,我试图手动添加每个属性,但没有任何效果。我可以得到任何提示或建议吗?

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
    ...
}

保存新产品输入.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 发送请求中的文件,并将 processDatacontentType 设置为 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");
    }
});

关于javascript - 对于 Controller 的 Ajax Post 方法,参数作为空值传入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59044524/

相关文章:

Javascript 和 Actionscript 3 [设置变量问题]

c# - Windows 应用商店应用、加密、提供的用户缓冲区对于请求的操作无效

c# - 如何在 ASP.NET MVC 中启用跨源请求

javascript - Jquery 自动完成选择事件

javascript - 响应 Firefox Add-on 中的地址栏按键事件

javascript - 尝试检测任何选中的值是否包含特定字符串

c# - 我的 Microsoft.Windows.Themes 程序集在哪里?

c# - WPF - 将参数从对话框窗口传递给用户控件

asp.net-mvc - 无法使 Web API 应用程序在 Windows 2008 服务器上工作

javascript - 在 jquery Mobile 中获取表单 ID 'pageshow'