如何使用Ajax获取MVC Json结果并填充到表中

时间:2014-06-25 11:12:41

标签: javascript jquery ajax asp.net-mvc json

我需要了解如何获取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')。click(function(){

GetContact();

});

我需要一些关于如何使用jQuery和AJAX的帮助,因为我无法弄清楚问题是否正在形成,请非常感谢你...

2 个答案:

答案 0 :(得分:6)

您可以尝试以下方法:

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();        
});

Working Demo

答案 1 :(得分:0)

这个插件简单易用的柠檬:

https://github.com/jongha/jquery-jsontotable