【发布时间】: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