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

前端 未结 2 666
陌清茗
陌清茗 2021-02-03 13:32

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 GetAllContac         


        
相关标签:
2条回答
  • 2021-02-03 13:39

    Easy peasy lemon squeezy with this plugin:

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

    0 讨论(0)
  • 2021-02-03 13:56

    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

    0 讨论(0)
提交回复
热议问题