Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 945
user3652878 Avatar asked Jun 25 '14 11:06

user3652878


People also ask

How can get JSON data from Controller using AJAX in MVC?

Create target "JSON object Mapper" object class file according to the business requirements. Create a "Controllers\HomeController. cs" file with default Index method and GetData(...) method with string type input query parameters for Ajax call with following lines of code i.e.

How JSON fetch data using AJAX?

getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. data − This optional parameter represents key/value pairs that will be sent to the server. callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.

How show JSON data table in HTML MVC?

Right click on Controller folder in the created MVC application, give the class name Home or as you wish and click OK. In the above controller class JsonResult method EmpDetails we have added the records into the Generic list and returning it as JSON to avoid database query for same result.


1 Answers

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

like image 198
chridam Avatar answered Oct 03 '22 05:10

chridam