将多个JSON对象传递给MVC3操作方法

Sen*_*ude 15 jquery json asp.net-mvc-3

JQuery代码:


    //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代码(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; }
    }
Run Code Online (Sandbox Code Playgroud)

现在的问题是,我无法通过将"CategoryMode","ProductModel"传递给"ModelTwo"动作方法来实现它.JQuery帖子正确识别动作方法"ModelTwo",但"cat","prd"属性值为null.尽管遇到该方法,"CategoryID","CategoryName","ProductID","ProductName"都是null.


    //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);
                }
            });
        });

那么我的第一个JQuery调用"ModelTwo"动作方法出了什么问题呢?

我花了很多时间搞清楚这一点,但不确定发生了什么.这里的路由没有问题,因为我可以找到正确的行动方法......

任何帮助将不胜感激.

谢谢!

Dar*_*rov 38

您可以将它们作为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);
    }
});
Run Code Online (Sandbox Code Playgroud)

JSON.stringify我在我的示例中使用的方法本身内置于所有现代浏览器中,但如果您需要支持旧版浏览器,则可以将json2.js脚本包含在您的页面中.

这应该正确绑定到以下操作:

[HttpPost]
public ActionResult ModelTwo(Category cat, Product prd)
{
    return Json(new { message = "this took multiple model..." });
}
Run Code Online (Sandbox Code Playgroud)

但我建议你定义一个视图模型:

public class MyViewModel
{
    public Category Cat { get; set; }
    public Product Prd { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后让您的控制器操作采用此视图模型:

[HttpPost]
public ActionResult ModelTwo(MyViewModel model)
{
    return Json(new { message = "this took a single view model containing multiple models ..." });
}
Run Code Online (Sandbox Code Playgroud)

当然,客户端代码保持不变.