Muhammad Kamran Muhammad Kamran - 3 months ago 7
jQuery Question

I want to read values from List<long> using Ajax and assign to different HTML element

Hi everyone i want to read the value from List i have static method which i call in action result method. That method is called by ajax call. I am returning multiple integer values which i want to show in different HTML elements.here is my code.

public static List<long> GetCounter()
{
try
{
var listofcounters = new List<long>();
using (var db = new DatabaseContext())
{
var usercount = db.User.Select(x => x).Count();
var usercountpending = db.User.Count(x => x.IsApproved == false);
var visitercounts = db.SiteViewers.Count();
var todayvisitscount = db.SiteViewers.Count(x => x.VistedDate == DateTime.Now);
listofcounters.Add(usercount);
listofcounters.Add(usercountpending);
listofcounters.Add(visitercounts);
listofcounters.Add(todayvisitscount);
return listofcounters;
}
}
catch (Exception ex)
{
throw ex;
}
}


[HttpGet]
public ActionResult CounterValues()
{
try
{
var listofcounters = SuperUserManager.GetCounter();
return Json(listofcounters, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw ex;
}
}



MY AJAX CALL


function UpdateDashboard() {
$.ajax({
type: "GET",
url: '../Admin/AdminHome/CounterValues',
async: true,
success: function (data) {
$('#labeluser').text(usercount);
$('#labelpendinguser').text(pendinguser);
}
});


}

Please help me with this. Please do not down vote my question or mark as duplicate. Thank you

Answer

Your current code is going to return an array like [234,456,768]. Now you do no't know which item in the array is UserCount (well, you know if you look at the server code and find the order. But it is not clearly readable code!)

I suggest you create a simple POCO to represent the data you want to send

public class DashboardVm
{
   public long UserCount { set;get;}
   public long PendingUserCount { set;get;}
   public long VisiterCount  { set;get;}
}

Have your GetCounter method returns an instance of this instead of the list of long.

public DashboardVm GetCounter()
{
    var vm=new DashboardVm();
    try
    {
        using (var db = new DatabaseContext())
        {
            vm.UserCount = db.User.Select(x => x).Count();
            vm.PendingUserCount = db.User.Count(x => x.IsApproved == false);
            // TO DO : Set other property values as well              
        }
        return vm;
    }
    catch (Exception ex)
    {
        // to do : Log the error so you know what went wrong
        throw;
    }
} 

and return the result of this method call instead of the array.

public ActionResult CounterValues()
{
  var vm=GetCounter();
  return Json(vm, JsonRequestBehavior.AllowGet);
}   

Now in your ajax method's success callback, you can access it like

success : function(data){
    $('#labeluser').text(data.UserCount);
    $('#labelpendinguser').text(data.PendingUserCount);
}