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

时间:2012-03-04 21:11:14

标签: 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; }
    }

现在的问题是,我无法通过将“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”动作方法有什么问题?

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

非常感谢任何帮助。

谢谢!

2 个答案:

答案 0 :(得分:36)

您可以将它们作为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);
    }
});

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

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

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

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

public class MyViewModel
{
    public Category Cat { get; set; }
    public Product Prd { get; set; }
}

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

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

当然客户端代码保持不变。

答案 1 :(得分:-1)

 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