jQuery 将多个 JSON 对象传递给 MVC3 操作方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9558848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass multiple JSON objects to MVC3 action method
提问by Sensbile Dude
JQuery code:
查询代码:
//This passes NULL for "CategoryID", "CategoryName", "ProductID", "ProductName" $("#btnPost").click(function () { var CategoryModel = { CategoryID: 1, CategoryName: "Beverage" }; var ProductModel = { ProductID: 1, ProductName: "Chai" }; var data1 = {}; data1["cat"] = CategoryModel; data1["prd"] = ProductModel; var jsonData = JSON.stringify(data1); $.ajax({ url: url + '/Complex/ModelTwo', //This works but property values are null type: 'post', dataType: 'json', data: { "cat": CategoryModel, "prd": ProductModel }, //jsonData, cache: false, success: function (result) { alert(result); }, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); } }); });
MVC Code (C#):
MVC 代码 (C#):
public class ComplexController : Controller
{
public string ModelOne(Category cat)
{
return "this took single model...";
}
public string ModelTwo(Category cat, Product prd)
{
return "this took multiple model...";
}
}
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
}
Now the issue is, I couldn't get it working by passing "CategoryMode", "ProductModel" into "ModelTwo" action method. The JQuery post correctly identifies the action method "ModelTwo" but "cat", "prd" property values are null. "CategoryID", "CategoryName", "ProductID", "ProductName" all are null despite hitting that method.
现在的问题是,我无法通过将“CategoryMode”、“ProductModel”传递给“ModelTwo”操作方法来使其工作。JQuery 帖子正确标识了操作方法“ModelTwo”,但“cat”、“prd”属性值为空。“CategoryID”、“CategoryName”、“ProductID”、“ProductName”尽管点击了该方法,但都是空的。
//THIS ONE WORKS FINE... $("#btnPost").click(function () { var CategoryModel = { CategoryID: 1, CategoryName: "Beverage" }; var ProductModel = { ProductID: 1, ProductName: "Chai" }; var data1 = {}; data1["cat"] = CategoryModel; data1["prd"] = ProductModel; var jsonData = JSON.stringify(data1); $.ajax({ url: url + '/Complex/ModelOne', //This works type: 'post', dataType: 'json', data: CategoryModel, cache: false, success: function (result) { alert(result); }, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); } }); });
So what's wrong with my first JQuery call to "ModelTwo" action method?
那么我对“ModelTwo”操作方法的第一次 JQuery 调用有什么问题呢?
I spent lots of time figuring this out, but not sure what's going on. There is no issue with routing here because I can land on the right action method...
我花了很多时间弄清楚这个,但不确定发生了什么。这里的路由没有问题,因为我可以找到正确的操作方法......
Any help will be greatly appreciated.
任何帮助将不胜感激。
Thanks!
谢谢!
回答by Darin Dimitrov
You could send them as JSON request:
您可以将它们作为 JSON 请求发送:
var categoryModel = {
categoryID: 1,
categoryName: "Beverage"
};
var productModel = {
productID: 1,
productName: "Chai"
};
$.ajax({
url: '@Url.Action("ModelTwo")',
type: 'post',
dataType: 'json',
// It is important to set the content type
// request header to application/json because
// that's how the client will send the request
contentType: 'application/json',
data: JSON.stringify({ cat: categoryModel, prd: productModel }),
cache: false,
success: function (result) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
The JSON.stringify
method that I am using in my example is natively built-in all modern browsers but if you need to support legacy browsers you could include the json2.jsscript to your page.
JSON.stringify
我在示例中使用的方法是所有现代浏览器本机内置的,但如果您需要支持旧版浏览器,您可以将json2.js脚本包含在您的页面中。
This should correctly bind to the following action:
这应该正确绑定到以下操作:
[HttpPost]
public ActionResult ModelTwo(Category cat, Product prd)
{
return Json(new { message = "this took multiple model..." });
}
But I would recommend you defining a view model:
但我建议你定义一个视图模型:
public class MyViewModel
{
public Category Cat { get; set; }
public Product Prd { get; set; }
}
and then have your controller action take this view model:
然后让您的控制器操作采用此视图模型:
[HttpPost]
public ActionResult ModelTwo(MyViewModel model)
{
return Json(new { message = "this took a single view model containing multiple models ..." });
}
and of course the client side code stays the same.
当然客户端代码保持不变。
回答by SanH
var a = $("#a").serialize();
var b = $("#b").serialize();
var c = $("#c").serialize();
$.ajax(
{
url: '@Url.Content("~/Controller/Method1")',
type: 'POST',
data: a+b+c,
success: function (success) {
// do something
}
});
// in Controller
[HttpPost]
public ActionResult Method1(abc a, bcd b, xyz c)
{
}
// where abc, bcd xyz are class