Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

javascript - 用于Ajax Post方法到Controller的参数为null(Parameters are coming in as null for Ajax Post method to Controller)

I have this bit of code that triggers on click.(我有这段代码会在点击时触发。)

When I set a breakpoint at SaveNewProduct all the values are null.(当我在SaveNewProduct处设置断点时,所有值均为null。) I tried to create a input object, I tried to add in each property manually, nothing worked.(我尝试创建一个输入对象,尝试手动添加每个属性,但没有任何效果。) May I get any tips or suggestion.(请问我有什么提示或建议。) 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(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; } } I also tried remove processData, i Am presented with this error Uncaught TypeError: Illegal invocation(我也尝试删除processData,出现此错误Uncaught TypeError: Illegal invocation)   ask by Master translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use FormData to send files in request with processData and contentType set to false(您需要使用FormDataprocessDatacontentType设置为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"); } });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...