如何使用Ajax获取MVC Json结果并填充到表中
how Get MVC Json Result and populate in a Table using Ajax
我需要一个关于如何我可以得到我的MVC Json结果和填充它在我的视图表使用Ajax的想法,
这是我的json结果
public JsonResult GetAllContacts()
{
var User = GetLoggedInUserID();
var getContact = _contactService.GetUserContacts(User).Select(x => new
{
Id = x.Id,
Name = x.Name,
MobileNumber = x.MobileNumber
});
return Json(getContact, JsonRequestBehavior.AllowGet);
}
请问我如何存档这个?
其次,我的表有复选框,我将能够选择手机号码,并将它们填充到一个列表框
这是我的表视图
<table class="table table-striped table-hover table-bordered" id="contacts">
<thead>
<tr>
<th><input type="checkbox" name="chooseAllRecipient" id="chooseAllRecipient" /></th>
<th class="center">Contact Name(s)</th>
<th class="center">Mobile Number(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="chooseRecipient" class="my_chkBox"></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
这是我的脚本
function GetContact() {
$.ajax({
url: table.data('/Contact/GetAllContacts'),
type: 'GET',
contentType: 'application/json',
data: JSON.stringify(),
cache: false,
context: table,
success: function (contact) {
var tableBody = this.find('tbody');
tableBody.empty();
$.each(contact, function (index, contact) {
$('<tr/>', {
html: $('<td/>', {
html: contact.Name
}).after($('<td/>', {
html: contact.MobileNumber
}))
}).appendTo(tableBody);
});
},
error: function () { alert("error"); }
});
}
$("# getContacts")。点击(function () {
GetContact();
});
请,我需要一些帮助,如何得到这个工作与jQuery和AJAX,因为我不知道问题是来自请非常感谢你…
您可以尝试以下操作:
public JsonResult GetAllContacts()
{
var user = GetLoggedInUserID();
var contacts = _contactService.GetUserContacts(user).Select(x => new
{
Id = x.Id,
Name = x.Name,
MobileNumber = x.MobileNumber
}).ToList(); // <--- cast to list if GetUserContacts returns an IEnumerable
return Json(contacts, JsonRequestBehavior.AllowGet);
}
在您的视图中,将此JSON数据填充到网格中: