Передавать несколько объектов JSON методу действия MVC3
Код 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 (С#):
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; }
}
Теперь проблема заключается в том, что я не мог заставить ее работать, передав "MethodModel", "ProductModel" в метод действия "ModelTwo" . Сообщение JQuery правильно идентифицирует метод действия "ModelTwo" , но значения свойств "cat", "prd" равны null. "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);
}
});
});
Итак, что случилось с моим первым вызовом JQuery к методу действий "ModelTwo" ?
Я потратил много времени на это, но не уверен, что происходит. Здесь нет проблем с маршрутизацией, потому что я могу приземлиться на правильный метод действия...
Любая помощь будет принята с благодарностью.
Спасибо!
Ответы
Ответ 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 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 script на вашу страницу.
Это должно быть правильно привязано к следующему действию:
[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 ..." });
}
и, конечно, код на стороне клиента остается прежним.
Ответ 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