jQuery代码:传递多个JSON对象MVC3操作方法
//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 post正确地标识了动作方法“ModelTwo”,但“cat”,“prd”属性值为null。 “类别ID”,“类别名称”,“产品ID”,“产品名称”均为空,尽管碰到该方法。
//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”动作方法有什么问题?
我花了很多时间搞清楚这一点,但不知道发生了什么事。这里没有路由问题,因为我可以登陆正确的行动方法...
任何帮助将不胜感激。
谢谢!
这太棒了!!!!!!有效。没有单个参数版本的“ContentType”设置,它工作得很好,但是双倍。我必须做的唯一改变是使数据的字符串化像你提到的那样传递,而不是整个模型本身“JSON.stringify({cat:CategoryModel,prd:ProductModel})”帮助了很多。你让我的一天达林!非常感谢! – 2012-03-04 22:30:37
我知道它有一个包装类,它具有Category和Product类的“get set”。对于单参数版本它工作得很好,但是当我传递两个参数时。但无论如何,你的建议帮助,我不得不添加contentType为两个参数化操作方法的json。谢谢! – 2012-03-04 22:36:46
这工作在Firefox?它在IE浏览器工作得很好,但Firefox。它没有在动作控制器中着陆,当我使用Fiddler找出数据传递给控制器时,只是空白。顺便说一下,我的控制器操作方法驻留在不同的项目中,所以它跨域发布。只要action方法只有一个参数,但只有两个参数,它就可以工作。将数据传递给控制器跨域时出错。 – 2012-03-05 20:36:44