Bri*_*n J 1 c# asp.net-mvc json model-binding
我使用模型对象列表创建了一个表.然后在单击该行上的按钮时将行数据传递到Ajax帖子.
在Ajax Post .stringify中调用传递的行数据.当我检查Dev Tools中传递的数据的值时,我可以看到它们已被填充:
["66", "jdoe@gmail.com", "2009", "test",…]
0
:
"66"
1
:
"jdoe@gmail.com"
2
:
"2009"
3
:
"test"
Run Code Online (Sandbox Code Playgroud)
但是当我进入从客户端调用的控制器POST操作时.预期的JSON字符串为null/empty.我的想法是,这可能是因为stringify没有与数组中的每个值相关联的属性名称.
题:
如何解析传递给mvc控制器的null 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; }
}
Run Code Online (Sandbox Code Playgroud)
表和AJAX post方法:
<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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
最后是MVC控制器中的POST方法:
[HttpPost]
public ActionResult updateStatus(stirng jsonString)
{
//deserialise the json to a Status object here
}
Run Code Online (Sandbox Code Playgroud)
需要创建控制器以接受实际对象,而不是json字符串.
我的意思是这个
[HttpPost]
public ActionResult updateStatus(stirng jsonString)
{
//deserialise the json to a Status object here
}
Run Code Online (Sandbox Code Playgroud)
应该
[HttpPost]
public ActionResult updateStatus(Status vm)
{
//no need to deserialize - was already done by the model binder
}
Run Code Online (Sandbox Code Playgroud)
为了让模型绑定器绑定您的json,Status您需要传递一个复制viewmodel的json对象.
{
ID:yourId,
Contact_Email:yourContactEmail,
RID:YourRID,
Name:yourName
}
Run Code Online (Sandbox Code Playgroud)
在伪代码中,您可以:
var statusData = {
ID:tableData[0],
Contact_Email:tableData[1],
RID:tableData[2],
Name:tableData[3]
};
Run Code Online (Sandbox Code Playgroud)
然后在你的ajax电话中,
data: JSON.stringify(statusData),
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
843 次 |
| 最近记录: |