how Get MVC Json Result and populate in a Table using Ajax

41,539

You could try the following:

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

In your view, populate this JSON data into the grid:

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

EDIT: adding extra requirement for populating mobile numbers from selected checkboxes to listbox

$("#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

Share:
41,539
user3652878
Author by

user3652878

Updated on August 15, 2022

Comments

  • user3652878
    user3652878 over 1 year

    I need an idea on how I can GET my MVC Json result and populate it inside my view table using Ajax,

    this is my json result

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

    Please how can I archieve this?

    Secondly My Table has Checkboxs that I will be able to pick the Mobile number and populate them inside a Listbox

    this is my table view

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

    });

    please I need some help on how to get this working with jQuery and AJAX because I can't figure out were the problem is coming form please thank you very mush...

  • user3652878
    user3652878 almost 10 years
    Thank you very mush... now I can populate perfectly... One more thing please, that table has a button that when those checkboxes are selected it should get the mobile number into a listbox... so please can you just complete that for me on that fiddle Demo please God bless you thank you very mush
  • chridam
    chridam almost 10 years
    Glad it helped. Perhaps you could add a separate question for that?
  • user3652878
    user3652878 almost 10 years
    <div class="center"><a class="btn btn-success btn-large" data-dismiss="modal" aria-hidden="true" id="addRecipientList">Add To Recipient List</a></div> this is the list box ` @Html.ListBoxFor(model => model.SelectedRecipient, Model.Recipients, new { id = "recipientList", style = "width: 250px; height: 160px;", name = "recipientList" }) `
  • user3652878
    user3652878 almost 10 years
    Every thing is okay now Please can I get your email so I can get to you direct [email protected]
  • chridam
    chridam almost 10 years
    Do you mean to remove a number from the list box? You would typically need to first select the option (or do a multiple selection) then click on another button to remove the number.
  • user3652878
    user3652878 almost 10 years
    No, I mean Checking for existing Number not to repeat it self when adding again...