Search code examples
asp.net-mvcweb-serviceshtml-generation

Any ideas what the best method would be to update a block of complex View-generated HTML via AJAX in MVC?


I have a bunch of code in my old Web Forms app I'm migrating to MVC. There are sections of various pages that need to have HTML generated by the view and then regenerated by an AJAX call. A lot of this HTML is pretty complex, so it really helps to keep all of the html generation in one spot (preferrably a template).

My question is, is there a better approach to this? Should I be using partial views or something? How would that translate into the WebService call? Is there something more efficient I could be doing?

Basically this is what I'm doing now (this is a really basic, crappy, example so I apologize):

In Pseudo-code:

The Markup

<!--- some html here -->
<div id="myContent">
  <%=StaticMethods.GetContent()%>
</div>
<button id="btnUpdate">Update</button>
<!--- some html here -->

The AJAX Javascripty stuff

$(document).ready(function() {
   $('#btnUpdate').click(function() {
      $.ajax({
         url:'MyService.asmx/MyWebServiceMethod',
         /*crap here*/
         success: function(result, status, code) {
            $('#myContent').html(result);
         }
      });
   });
});

The Static Method

public static class StaticMethods {
   public static string GetContent() {
      var sb = new StringBuilder();
      var somethings = GetSomeRandomThings(); 
      //just an example. it's normally much more complex.
      foreach(var something in somethings) {
          sb.AppendFormat("<li>{0}</li>",something.Name);
      }
   }
}

MyWebService

public string MyWebServiceMethod() {
    return StaticMethods.GetContent();
}

Solution

  • You can use partial views. But remember that you must pass the data to the partial view. If your partial view is used everywhere it could be complex.

    If you want something more independent, you can use the MVC Future's "RenderAction()" to make a partial view act like a call to a regular action. So the "partial view" does not have a dependency to the current action being rendered.

    See the difference here: http://blogs.intesoft.net/post/2009/02/renderaction-versus-renderpartial-aspnet-mvc.aspx

    Personally, I would use RenderAction() for the initial rendering of the page. The AJAX calls to update the panel would point to the same action of the RenderAction call.

    Mike