【问题标题】:How to resolve null json string passed to mvc controller?如何解析传递给 mvc 控制器的空 json 字符串?
【发布时间】:2017-02-01 09:09:45
【问题描述】:

我使用模型对象列表创建了一个表。 然后在单击该行上的按钮时将行数据传递给 Ajax 帖子。

在 Ajax 帖子中,.stringify 会在传递下来的行数据上被调用。 当我在 Dev Tools 中检查线路上传递的数据值时,我可以看到它们已被填充:

["66", "jdoe@gmail.com", "2009", "test",…]
0
:
"66"
1
:
"jdoe@gmail.com"
2
:
"2009"
3
:
"test"

但是当我进入从客户端调用的控制器 POST 操作时。预期的 JSON 字符串是 null / empty。 我的想法是,这可能是因为 stringify 没有与数组中的每个值相关联的属性名称。

问题:

如何解析传递给 mvc 控制器的空 json 字符串?

下面是实现的要点-

型号:

public class Status
{

        [Key]
        public int ID { get; set; }


        public string Contact_Email { get; set; }

        public string RID { get; set; }

        public string Name { get; set; }



    }

表格和AJAX发布方式:

     <table id="statusTable" class="table table-hover table-bordered results">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Email</th>
                    <th>RID</th>
                    <th>Name</th>
                    <th>Update Record</th>


                </tr>
            </thead>
            <tbody>
            @foreach (var row in Model.ReleaseStatus)
            {
                    <tr>
                        <td>@Html.Raw(row.ID)</td>
                        <td>@Html.Raw(row.Contact_Email_Name)</td>
                        <td>@row.RID</td>
                        <td>@row.Name</td>
                        <td><button type="submit" class="btn btn-success">Update</button></td>
                    </tr>
              }
            </tbody>

        </table>



 $(".btn-success").click(function () {
            var $td = $(this).closest('tr').children("td"),
            len = $td.length;
            var tableData = $td.map(function (i) {
                if (i < len - 1)
                    return $(this).text();
            }).get();

            console.log(tableData);

            //Post JSON data to controller
            $.ajax({
                type: "POST",
                url: 'updateStatus',
                data: JSON.stringify(tableData),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    console.log("post success");
                },
                error: function (request) {
                    console.log("post error" + request.error);
                }

            });


        });

最后是 MVC 控制器中的 POST 方法:

    [HttpPost]
    public ActionResult updateStatus(stirng jsonString)
    {
        //deserialise the json to a Status object here
    }

【问题讨论】:

  • 你为什么要绑定到string 而不是你的模型。你的方法应该是public ActionResult updateStatus(Status model) 和数据var data = { ID: 66, Contact_Email: 'jdoe@gmail.com', etc }
  • 我确实尝试在 mvc 操作中指定一个对象,例如 updateStatus(Status vm) 在发布期间该对象为空。我认为主要问题是我在 jquery 中传递的数据没有附加到值的名称?
  • 是的,这就是为什么你需要生成和对象(根据我之前的评论)并在 ajax 中删除 contentType: "application/json; charset=utf-8", 并使用 data: data,
  • 但是您没有编辑模型的任何属性,这有什么意义呢?

标签: c# json asp.net-mvc model-binding


【解决方案1】:

您的控制器需要被创建来接受实际的对象,而不是 json 字符串。

我的意思是

[HttpPost]
public ActionResult updateStatus(stirng jsonString)
{
   //deserialise the json to a Status object here
}

应该是

[HttpPost]
public ActionResult updateStatus(Status vm)
{
   //no need to deserialize - was already done by the model binder
}

为了让模型绑定器将您的 json 绑定到 Status,您需要传递一个复制您的视图模型的 json 对象。

{
 ID:yourId, 
 Contact_Email:yourContactEmail, 
 RID:YourRID, 
 Name:yourName
}

在伪代码中,您可以:

var statusData = {
     ID:tableData[0], 
     Contact_Email:tableData[1],
     RID:tableData[2], 
     Name:tableData[3]
};

然后在你的ajax调用中,

data: JSON.stringify(statusData),

【讨论】:

  • 这不会做任何事情,除非 OP 也在视图中正确生成对象而不是回发数组
  • 我尝试在json字符串之前传入一个Status对象,对象中的每个值在到达action方法时都是null。我认为是因为我的数据没有指定每个值的名称?
  • @BrianJ - 我添加了更多解释来解释为什么你会得到空值。这就是斯蒂芬在对此答案的评论中所指的内容。
  • @BrianJ,您当前的所有帖子都是一组值 - 它可以 b=never 序列化为 List&lt;object&gt; 以外的任何内容(添加 [DisplayName] 不会解决问题)
  • @BrianJ - 为你的约会做这个。 Create_Date: new Date(tableData[5]) - 给它一个实际的日期。
【解决方案2】:

试试 from body 属性

[HttpPost]
public ActionResult updateStatus([FromBody]Status status)
{
    //add the serialize attribute on your model 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2014-04-01
    相关资源
    最近更新 更多