【问题标题】:Model Binding from a Form从表单绑定模型
【发布时间】:2013-09-21 06:18:56
【问题描述】:

我正在尝试将 json 绑定到我在 ASP .net MVC 4 中的模型。模型确实已创建,但属性未填充。

我的javascript:

   $.ajax({
     type: 'POST',
        url: "/Admin/" + method,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(form.serializeArray()),
        success: function (data) {
            if (data.Success == true) {


            }
        }
    });

我的班级:

public class Taxes {
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Rate { get; set; } }

我的方法:

[HttpPost]
public JsonResult AddTax(Taxes tax)
{

    return Json(new { Success = true, tax.Id });
}

Json:

[{"name":"Id","value":"1"},{"name":"Name","value":"fsdfs"},{"name":"Rate","value":"18"}]

结果是:

Id = 0
Name = Null
Rate = 0

【问题讨论】:

  • 你能解释一下你已经尝试过什么吗?
  • 试试这个 json,它将填充你的模型 [{"Id":"1","Rate":"18", "Name":"fsdfs"}]。

标签: c# asp.net asp.net-mvc json asp.net-mvc-4


【解决方案1】:

好吧,您已经写出了您的问题所在,但您只是没有阅读它。您的来电 JSON.stringify(form.serializeArray()) 正在为你生成这个:

[{"name":"Id","value":"1"},{"name":"Name","value":"fsdfs"},{"name":"Rate","value":"18"}]

只能映射到这样的东西:

IEnumerable<SampleClass> model

SampleClass 的属性:

public class SampleClass
    {
         public string name {get;set;}
         public string value {get;set;}
    }

您需要不同类型的方法,其中一种:

  1. 为您创建 javascript 对象
  2. 对于使用 form.serializeArray() 创建的数组的每个成员,它将 将属性添加到名称为 member.name 和值的对象 member.value

JSON.stringify 然后将生成您的 Taxes 类的正确 JSON 表示。

在此处检查实现:

https://github.com/hongymagic/jQuery.serializeObject

【讨论】:

    猜你喜欢
    • 2013-05-28
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    • 2013-07-13
    • 2014-12-02
    相关资源
    最近更新 更多