In a page that has a grid/list dynamically loaded via AJAX, an efficient way to populate that list would be to call a controller action to that returns a JSON result.
With ASP.net MVC, you could call a controller action that returns a partial page, but that doesn't seem efficient since it returns chunks of HTML. Using JSON would result in returning data that is much more compact in size. What is the best way to render the page using just JSON results and jquery, using some sort of loop to parse and format the results? Most of the examples I've found online simply suggest returning a partial list, which may be suitable for trivial uses, but all the big sites I've seen use pure JSON to populate their AJAX lists.
Partial HTML Result (seems inefficient to return such a large result):
<div>
<img src="myimage.jpg">
Category Description
</div>
<div>
<img src="myimage2.jpg">
Category Description 2
</div>
etc...
JSON Result:
[{"image" : "myimage.jpg", "category" : "Category Description"}]
That said, currently I have :
public PartialViewResult CategoryListPartial(string category)
{
var filteredCategories = DB.Categories.OrderBy(c => c.Name)
.Where(c => c.Category.Name == category);
return PartialView("CategoryListPartial", filteredCategories);
}
And the following client side jquery to load the list with a loading image
$.get('@Url.Action("CategoryListPartial","Categories", new {category="Toys"})',
function (data) {
$('.ajaxResponse').empty().html('<img src="/contents/images/loader.gif"');
$('.ajaxResponse').replaceWith(data);
});
I assume it would be better to have:
[HttpPost]
public PartialViewResult CategoryListPartial(string category)
{
var filteredCategories = DB.Categories.OrderBy(c => c.Name).
Where(c => c.Category.Name == category);
return Json(results);
}
With the matching client side iterate and format the JSON results:
$.get('@Url.Action("CategoryListPartial","Categories", new { category = "Toys" } )', function (data) {
// <pseudocode begin>
for each item in data
render <div><table><tr>...
category.Image = item.Image
category.Name = item.Name
end render
// <pseudocode end>
});
Is there a standard way of achieving this?