Ruz
Ruz

Reputation: 33

Using ASP.net MVC and jquery to populate AJAX lists using JSON instead of full partial page HTML

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?

Upvotes: 0

Views: 1975

Answers (2)

Eduardo Wada
Eduardo Wada

Reputation: 2647

There's a class called JsonResult (System.Web.Mvc), can't you just use that?

you would get a controller method like

public JsonResult getData()
{
    var myData = new {foo= "foo", bar= "bar"};
    return Json(myData);
}

and a call like

var url = '@Url.Action("getData", "Home")';

$.post(url,
    function (data) {
        alert(data.foo);
        alert(data.bar);
    }
);

Note: JsonResult answers only to Post by default

Upvotes: 1

JayC
JayC

Reputation: 7141

Standard? No, I don't know of a standard way to do this, but yes, that's what some of the Javascript MVC frameworks do (like Backbone.js). I haven't tried any of the others I've heard about ( JavascriptMVC, Knockout.js, etc.) Or maybe you're not interested in the full MVC but just Javascript Templating? Backbone does have that through Underscore.js, but it's certainly not the only one (jQuery apparently has it's own), and then there's also Mustashe.js

That enough for you? :-D

Upvotes: 1

Related Questions