Hanady Hanady - 4 months ago 21
Ajax Question

Get model count in ajax response returning Partial View

I am calling a method named

Issues
in
Issues
controller through ajax.

var url = "@(Url.Action("Issues", "Issues"))";
$.ajax({
type: 'POST',
url: url,
data: issue,
dataType: "html",
success: function (evt) {
$('#filteredDataList').html(evt);
},
});


And in my controller:

[System.Web.Mvc.HttpPost]
public ActionResult Issues(IssuesModel issue)
{
var model = allIssuesList.OrderBy(p => p.ID).ToList();
return PartialView("~/Views/Issues/_LoadMoreIssues.cshtml", model.Take(20));
}


What I need is a way to get the model count in the success response of the ajax call, so i can do the following:

success: function (evt) {
$('#filteredDataList').html(evt);
var modelCount = ???
if (modelCount > (20)) {
$("#loadMore").show().fadeIn(2000);
}
},...


Is there any possible way to achieve this?

Answer

You're not returning a model to the ajax call, you're returning html.

You can include any information you like in the html and read it from there.

First, add a viewmodel to include your additional information:

 public class MoreIssuesViewModel 
 {
     public IList<Order> Orders { get;set; }
     public int Total { get;set; }
 }

Use this from the controller:

[System.Web.Mvc.HttpPost]
public ActionResult Issues(IssuesModel issue)
{
    var data = allIssuesList.OrderBy(p => p.ID).ToList()
    var model = new MoreIssuesViewModel 
    {
        Orders = data.Take(20),
        Total = Orders.Count()
    }
    return PartialView("~/Views/Issues/_LoadMoreIssues.cshtml", model);
}

Then in your view, store the new information somewhere (example)

@model MoreIssuesViewModel
<table data-total='@Model.Total'>
  <tbody>    
      @foreach(var order in Model.Orders) {
         <td>....</td>
      }

You can then read this from the success

success: function (evt) {
    $('#filteredDataList').html(evt);
    var modelCount = $('#filteredDataList table').data("total")
    if (modelCount > (20)) {
        $("#loadMore").show().fadeIn(2000);
    }
},...
Comments