我可以 post 从 html.raw 到控制器的 JSON 模型吗?
Can I post a JSON model from html.raw to controller?
我有一个模型要传递给视图并使用 Html.Raw 将其编码为 JSON 对象:
var model = @Html.Raw(Json.Encode(Model));
在页面上,我从页面中的字段填充模型的各个部分:
model.ProductId = $("#txtProductId").val();
然后尝试 post 以 ajax 的方式将其发送到控制器:
$.ajax({
type: 'POST',
url: '@Utl.Action("AddProducts"),
data: JSON.stringify(model),
dataType: 'json',
//etc
但它永远不会进入控制器方法:
[HttpPost]
public ActionResult AddProducts(ProductModel, model)
{
//do stuff with the model data
}
任何人都可以帮我解释一下我必须如何更改才能使模型达到 post?
我的模型,简化:
public class OrderModel {
public ProductModel Product {get;set;}
public PersonModel Person {get;set;}
public List<ProductModel> Products {get;set;}
}
public class ProductModel {
public string Partno {get;set;}
public int Quantity {get;set;}
/// etc
}
public class PersonModel {
public string Surname {get;set;}
public string GivenName {get;set;}
public string Address {get;set;}
/// etc
}
将您的代码更改为
$.ajax({
type: 'POST',
url: '@Url.Action("AddProducts")',
data: model, // not stringified
dataType: 'json',
....
或
$.post('@Url.Action("AddProducts")', model, function(data) {
// do stuff with returned data
});
这将 post 返回到
[HttpPost]
public ActionResult AddProducts(ProductModel model)
{
//do stuff with the model data
}
假设您认为的模型是ProductModel
但是,如果您只想 post 返回表单,您可以使用 var model = $('form').serialize();
而不是手动设置对象的属性。
我有一个模型要传递给视图并使用 Html.Raw 将其编码为 JSON 对象:
var model = @Html.Raw(Json.Encode(Model));
在页面上,我从页面中的字段填充模型的各个部分:
model.ProductId = $("#txtProductId").val();
然后尝试 post 以 ajax 的方式将其发送到控制器:
$.ajax({
type: 'POST',
url: '@Utl.Action("AddProducts"),
data: JSON.stringify(model),
dataType: 'json',
//etc
但它永远不会进入控制器方法:
[HttpPost]
public ActionResult AddProducts(ProductModel, model)
{
//do stuff with the model data
}
任何人都可以帮我解释一下我必须如何更改才能使模型达到 post?
我的模型,简化:
public class OrderModel {
public ProductModel Product {get;set;}
public PersonModel Person {get;set;}
public List<ProductModel> Products {get;set;}
}
public class ProductModel {
public string Partno {get;set;}
public int Quantity {get;set;}
/// etc
}
public class PersonModel {
public string Surname {get;set;}
public string GivenName {get;set;}
public string Address {get;set;}
/// etc
}
将您的代码更改为
$.ajax({
type: 'POST',
url: '@Url.Action("AddProducts")',
data: model, // not stringified
dataType: 'json',
....
或
$.post('@Url.Action("AddProducts")', model, function(data) {
// do stuff with returned data
});
这将 post 返回到
[HttpPost]
public ActionResult AddProducts(ProductModel model)
{
//do stuff with the model data
}
假设您认为的模型是ProductModel
但是,如果您只想 post 返回表单,您可以使用 var model = $('form').serialize();
而不是手动设置对象的属性。