如何通过Ajax获取MVC Json结果并将其填充到表格中

8
我需要一个关于如何使用Ajax获取我的MVC Json结果并将其填充到我的视图表中的想法,
这是我的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>

and this is my Script

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').click(function () {

GetContact();

请帮我解决这个问题,我无法确定出错的地方,请使用jQuery和AJAX让其正常工作,谢谢!

注意:请勿删除html标签。


2
你有没有意识到你正在使用联系人作为数据参数和项目参数?它们的名称相同,这会导致函数混淆。更改一下,看看是否解决了问题。 - Fals
如@Fals所说,请将contact.Namecontact.MobileNumber更改为this.Namethis.MobileNumber - dklingman
我还有一个问题,那就是什么是“table”?我猜它是一个变量,但我猜你没有展示所有的JavaScript代码。 - dklingman
2个回答

12

你可以尝试以下方法:

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 数据填入网格中:

HTML

<table class="table table-striped table-hover table-bordered">
    <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 id="contacts"></tbody>
 </table>
 <button id="add_recipient">Add Selected Recipients</button>
 <select id="recipientList"></select>

jQuery

function GetContact() {    
    $.ajax({
        url: "/Contact/GetAllContacts",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function (data) {
            var row = "";
            $.each(data, function(index, item){
                row+="<tr><td><input type='checkbox'id='"+item.Id+"' name='chooseRecipient' class='my_chkBox' /></td><td>"+item.Name+"</td><td>"+item.MobileNumber+"</td></tr>";
            });
            $("#contacts").html(row);    
        },
        error: function (result) {
            alert("Error");
        }
    });
}

$('#getContacts').click(function(){
      GetContact();
});

编辑:添加了从选定复选框中填充移动电话号码到列表框的额外要求。

$("#add_recipient").click(function(e){
    e.preventDefault();
    $("#contacts input:checkbox:checked").map(function(){
        var contact_number = $(this).closest('td').next('td').next('td').text();
        var id = $(this).attr('id');
        $('#recipientList').append('<option value="'+ id +'">'+ contact_number +'</option>');              
    }).get();        
});

操作演示


非常感谢您...现在我可以完美地填充了...还有一件事情,请注意,当选择那些复选框时,该表格有一个按钮,它应该将手机号码放入列表框中...所以请您在那个演示的Fiddle上为我完成这个功能...愿上帝保佑您,非常感谢。 - user3652878
很高兴能帮到你。也许你可以单独提出一个问题来问这个? - chridam
<div class="center"><a class="btn btn-success btn-large" data-dismiss="modal" aria-hidden="true" id="addRecipientList">添加到收件人列表</a></div> 这是列表框@Html.ListBoxFor(model => model.SelectedRecipient, Model.Recipients, new { id = "recipientList", style = "width: 250px; height: 160px;", name = "recipientList" }) - user3652878
现在一切都好了。请问我能否得到您的电子邮件,以便我可以直接联系您?我的邮箱是7rippl3m@gmail.com - user3652878
你是指从列表框中删除一个数字吗?通常需要先选择该选项(或进行多重选择),然后点击另一个按钮来删除该数字。 - chridam
不,我的意思是检查现有的数字,以防在再次添加时重复出现... - user3652878

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接