title: Using ASP.net MVC and jquery to populate AJAX lists using JSON instead of full partial page HTML
body: <p>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. </p>
  
  <p>With ASP.net MVC, you <em>could</em> 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.</p>
  
  <p><em>Partial HTML Result (seems inefficient to return such a large result):</em></p>
  
  <pre><code>&lt;div&gt;
      &lt;img src="myimage.jpg"&gt;
      Category Description
  &lt;/div&gt;
  &lt;div&gt;
      &lt;img src="myimage2.jpg"&gt;
      Category Description 2
  &lt;/div&gt;
  etc...
  </code></pre>
  
  <p><em>JSON Result:</em></p>
  
  <pre><code>[{"image" : "myimage.jpg", "category" : "Category Description"}]
  </code></pre>
  
  <hr>
  
  <p>That said, currently I have :</p>
  
  <pre><code>public PartialViewResult CategoryListPartial(string category)
  {
      var filteredCategories = DB.Categories.OrderBy(c =&gt; c.Name)
                              .Where(c =&gt; c.Category.Name == category);
      return PartialView("CategoryListPartial", filteredCategories);
  }
  </code></pre>
  
  <p>And the following client side jquery to load the list with a loading image</p>
  
  <pre><code>$.get('@Url.Action("CategoryListPartial","Categories", new {category="Toys"})',  
     function (data) {
       $('.ajaxResponse').empty().html('&lt;img src="/contents/images/loader.gif"');
       $('.ajaxResponse').replaceWith(data);
   });
  </code></pre>
  
  <p>I assume it would be better to have:</p>
  
  <pre><code>[HttpPost]
  public PartialViewResult CategoryListPartial(string category)
  {
          var filteredCategories = DB.Categories.OrderBy(c =&gt; c.Name).
                                   Where(c =&gt; c.Category.Name == category);
          return Json(results);
  }
  </code></pre>
  
  <p>With the matching client side iterate and format the JSON results:</p>
  
  <pre><code>$.get('@Url.Action("CategoryListPartial","Categories", new { category = "Toys" } )', function (data) {
    // &lt;pseudocode begin&gt;
    for each item in data
    render &lt;div&gt;&lt;table&gt;&lt;tr&gt;...
              category.Image = item.Image
              category.Name = item.Name
    end render
    // &lt;pseudocode end&gt;
   });
  </code></pre>
  
  <p>Is there a standard way of achieving this?</p>