MVC3 - 通过 AJAX 和 POST 文件没有表单的 JSON
我有一个从客户端接收复杂 JSON 对象的操作方法。我在客户端序列化这个对象,由于复杂性,我不能(不想)使用表单提交来发布数据。
我还需要能够随该 ajax 请求一起发送文件。我的操作方法工作完美,并且使用 jQuery.ajax() 绑定 JSON 对象(实际上是对象列表)。当我移动到 ajax 表单插件 以便我可以发送文件时,对象绑定会中断。我尝试使用插件提交表单并将我的对象作为附加数据发送。操作方法不再看到我的对象。
关于如何将 JSON 和文件一起发布到同一操作方法有什么想法吗?
这是有效的 jQuery.ajax() 方法。这里没有提交表单,这只是将 JSON 数据发送到服务器,
$.ajax({
url: "/Controller/Create2",
type: 'POST',
data: JSON.stringify(model),
dataType: 'json',
contentType: 'application/json, charset=utf-8',
beforeSend: function () {
},
success: function (data) {
},
error: function () {
}
});
我的 Action 方法以这种方式完美地获取对象列表。
public ActionResult Create2(List<CreateModel> model)
{
//Do stuff
}
但是当我在表单上执行 ajax 提交并附加数据时,模型返回 null。
f.ajaxSubmit({
url: "/Controller/Create2",
type: "POST",
data: JSON.stringify(model),
dataType: 'json',
contentType: 'application/json, charset=utf-8',
beforeSend: function () {
},
success: function (data) {
},
error: function (data) {
}
});
我需要在 Action Method 中保留绑定 JSON 对象的功能,这是否意味着我必须放弃发布文件?
I have an Action Method that receives a complex JSON object from the client. I serialize this object on the client side and because of the complexity, I can't (don't want to) use a form submit to post the data.
I also need to be able to send files along with this ajax request. My action method works perfectly and binds the JSON object (actually List of objects) just fine using jQuery.ajax(). When I move to the ajax form plugin so that I can send files the object binding breaks. I attempt to submit the form with the plugin and send my object along as additional data. The action method no longer sees my object.
Any thoughts on how to post JSON and files together to the same action method?
Here's the jQuery.ajax() method that works. No form submit here, this is just sending JSON data to the server
$.ajax({
url: "/Controller/Create2",
type: 'POST',
data: JSON.stringify(model),
dataType: 'json',
contentType: 'application/json, charset=utf-8',
beforeSend: function () {
},
success: function (data) {
},
error: function () {
}
});
My Action method takes a List of objects perfectly this way.
public ActionResult Create2(List<CreateModel> model)
{
//Do stuff
}
But when I do an ajax submit on the form and append the data, the model comes back null.
f.ajaxSubmit({
url: "/Controller/Create2",
type: "POST",
data: JSON.stringify(model),
dataType: 'json',
contentType: 'application/json, charset=utf-8',
beforeSend: function () {
},
success: function (data) {
},
error: function (data) {
}
});
I need to retain the functionality of binding to JSON objects in the Action Method, does that mean I have to give up posting files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看 jQXB(http://www.jqxb.altervista.org 或 http://jqxb.codeplex.com )
Take a look at jQXB ( http://www.jqxb.altervista.org or http://jqxb.codeplex.com )