【问题标题】:Can I post a JSON model from html.raw to controller?我可以将 JSON 模型从 html.raw 发布到控制器吗?
【发布时间】:2015-01-22 17:56:30
【问题描述】:

我有一个模型要传递给视图并使用 Html.Raw 将其编码为 JSON 对象:

 var model = @Html.Raw(Json.Encode(Model));

在页面上,我从页面中的字段填充模型的各个部分:

 model.ProductId = $("#txtProductId").val();

然后尝试使用 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
 }

谁能在这里帮我解释一下我必须如何更改才能让模型发布?

我的模型,简化:

 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
  }

【问题讨论】:

  • 你为什么要调用stringify?不需要的
  • 好的,我的问题是什么?我尝试只发送模型,但得到了相同的结果,而不是发送到控制器方法。
  • 是的,内容类型应该是“application/json; charset=utf-8”
  • @AdrianSalazar contentType 已设置为该值,但仍然失败。还有其他想法吗?
  • 你有没有试过发送一个简单的字符串,看看是否能成功?

标签: ajax asp.net-mvc json


【解决方案1】:

将代码更改为

$.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
});

这将回发给

[HttpPost]
public ActionResult AddProducts(ProductModel model)
{
   //do stuff with the model data
}

假设你视图中的模型是ProductModel

但是,如果您只是想回发表单,您可以使用var model = $('form').serialize();,而不是手动设置对象的属性。

【讨论】:

  • 这就到了!它现在到达控制器,但是,模型对于设置的值是空的,例如从文本字段加载的 ProductId。列表是完整的,所以我知道模型没问题。有没有更好的方法来加载各个字段?
  • 对我来说很好。不确定列表完好无损 是什么意思?建议您发布模型定义以查看问题是否可能出在其他地方(典型问题是:没有 getter/setter、与控制器参数同名的属性、没有默认构造函数……)。您是否有理由不只是序列化表单?
  • 模型由 PersonModel 和 ProductModel 组成,其中包含名称和地址等字段,ProductModel 包含产品名称等字段,以及应该是集合的 ProductModels 条目订购的产品。因此,在页面中,我正在加载 model.PersonModel.Surname = $("#txtSuranem").val() 等。尽管我可以在发布之前在页面模型中清楚地看到它,但该数据永远不会到达控制器。产品模型被添加到产品模型数组 model.ProductModesl[cnt] = model.ProductModel,但最终为空。我正在尝试一次添加一个
  • 并显示部分视图,其中包含在表单的单独 DIV 中订购的产品列表。所以我不认为解决方案是序列化并发布整个表单,至少在用户完成订购之前不会,对吧?
  • 但是你的POST方法是ProductModel(绑定器不会绑定任何与PersonModel相关的值)。另外我怀疑您可能会以错误的方式处理此问题(如果您使用部分添加多个产品,肯定会使用重复的ids 创建无效的html)。您需要发布您的视图和传递给视图的模型的更多详细信息(一个新问题可能会更好)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
相关资源
最近更新 更多