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
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
Contact Name(s)
Mobile Number(s)
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+=""+item.Name+" "+item.MobileNumber+" ";
});
$("#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('');
}).get();
});
Working Demo