【问题标题】:Pass multiple JSON objects to MVC3 action method将多个 JSON 对象传递给 MVC3 操作方法
【发布时间】:2012-03-22 11:08:53
【问题描述】:

JQuery 代码:

//这为“CategoryID”、“CategoryName”、“ProductID”、“ProductName”传递NULL $("#btnPost").click(function () { var CategoryModel = { 类别ID:1, 类别名称:“饮料” }; 变种产品型号 = { 产品编号:1, 产品名称:“柴” }; 变量数据1 = {}; data1["cat"] = CategoryModel; data1["prd"] = 产品型号; var jsonData = JSON.stringify(data1); $.ajax({ url: url + '/Complex/ModelTwo', //这可行,但属性值为空 类型:'发布', 数据类型:'json', data: { "cat": CategoryModel, "prd": ProductModel }, //jsonData, 缓存:假, 成功:函数(结果){ 警报(结果); }, 错误:函数(xhr,ajaxOptions,throwError){ 警报(抛出错误); } }); });

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”属性值为空。 “CategoryID”、“CategoryName”、“ProductID”、“ProductName”都是空的,尽管点击了那个方法。

//这个工作正常... $("#btnPost").click(function () { var CategoryModel = { 类别ID:1, 类别名称:“饮料” }; 变种产品型号 = { 产品编号:1, 产品名称:“柴” }; 变量数据1 = {}; data1["cat"] = CategoryModel; data1["prd"] = 产品型号; var jsonData = JSON.stringify(data1); $.ajax({ url: url + '/Complex/ModelOne', //这行得通 类型:'发布', 数据类型:'json', 数据:类别模型, 缓存:假, 成功:函数(结果){ 警报(结果); }, 错误:函数(xhr,ajaxOptions,throwError){ 警报(抛出错误); } }); });

那么我对“ModelTwo”操作方法的第一次 JQuery 调用有什么问题?

我花了很多时间解决这个问题,但不确定发生了什么。这里的路由没有问题,因为我可以找到正确的操作方法...

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: jquery json asp.net-mvc-3


    【解决方案1】:

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

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

    【讨论】:

    • 这太棒了!!!!!!有效。它工作得很好,没有“ContentType”设置为单参数版本,但双。我必须做的唯一改变是像你提到的那样对传递的数据进行字符串化,而不是整个模型本身“JSON.stringify({ cat:CategoryModel,prd:ProductModel })”帮助很大。你让我的一天达林!非常感谢!
    • 我通过拥有一个具有“获取设置”类别和产品类的包装类来使其工作。它对于单参数版本工作得很好,但是当我传递两个参数时。但无论如何,您的建议有所帮助,我必须将 contentType 添加为 json 用于两个参数化操作方法。谢谢!
    • 这在 Firefox 中有效吗?它在 IE 中运行良好,但在 Firefox 中运行。它没有登陆动作控制器,当我使用提琴手找出正在传递给控制器​​的数据时,只是空白。顺便说一句,我的控制器操作方法驻留在不同的项目中,所以它是跨域发布。只要操作方法采用一个参数而不是两个参数,它就可以正常工作。跨域向控制器传递数据时出现问题。
    • @SensbileDude,您不能发送跨域 AJAX 请求。
    • 如果它是单个参数,它可以跨域成功运行,我让它在所有浏览器中运行。但是当我有两个属于类类型的参数时,将它们序列化以降落在正确的控制器上是行不通的。这是匹配传输到控制器的数据的问题。它在 IE 中工作,但在其他情况下。
    【解决方案2】:
     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
    

    【讨论】:

      猜你喜欢
      • 2012-06-02
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多