我正在尝试将我的 JSON 对象和两个输入文件字段从我的 View 传递回我的 MVC 4 Controller 。如果我在我的 ajax 中设置 async: true,
我会得到 JSON 对象但没有文件。如果我设置 async: false,
我得到的是文件,但没有 JSON。
关于为什么我不能将所有内容发送回我的 Controller 有什么想法吗?我正在尝试将图像上传到我的服务器。
另请注意,我的 JSON 永远不会返回成功,它总是会出错,但当 async: true,
时,值仍会传递给 Controller 。
任何帮助都会很棒,谢谢!
JSON:
var json = {Details:{"Name":"Person Name","Url":"http://stackoverflow.com/"};
Ajax :
$.ajax({
url: '/Admin/Create',
type: 'POST',
data: JSON.stringify(json),
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function () {
console.log('SUCCESS');
},
complete: function () {
console.log('COMPLETE');
}
});
Controller :
[HttpPost, ValidateInput(false)]
public ActionResult Create(AdminObjectModel jsonData,
IEnumerable<HttpPostedFileBase> images, IEnumerable<HttpPostedFileBase> small_images)
{
...
return Redirect("/admin/create");
}
HTML:
<form action="/Admin/Create" enctype="multipart/form-data" method="post">
...
<input type="file" id="images" class="span6" name="images" multiple />
...
<input type="file" id="small-images" class="span6" name="small_images" />
...
</form>
最佳答案
我想我想出了一个解决方案,不确定它是否是最好的,但它确实有效。
View > AJAX:
$.ajax({
url: '/Admin/CreateJSON',
type: 'POST',
data: JSON.stringify(json),
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
success: function () {
console.log('SUCCESS');
},
complete: function () {
console.log('COMPLETE');
}
});
查看 > HTML:
<form action="/Admin/Create" enctype="multipart/form-data" method="post">
...
<input type="file" id="images" class="span6" name="images" multiple />
...
<input type="file" id="small-images" class="span6" name="small_images" />
...
</form>
Controller :
private static AdminObjectModel create = new RecipeObjectModel();
[HttpPost, ValidateInput(false)]
public void CreateJSON(AdminObjectModel jsonData)
{
create = jsonData;
}
[HttpPost, ValidateInput(false)]
public ActionResult Create(IEnumerable<HttpPostedFileBase> images, IEnumerable<HttpPostedFileBase> small_images)
{
string t = create.Details.Name;
...
return Redirect("/admin/create");
}
关于c# - 将 JSON 和输入文件传回 Controller MVC 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23412244/