Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Asp mvc controller return html by Jquery Ajax to load dynamically html into div

Posted on: 2012-03-06

When it's time to load Html from the server side from Javascript, the best way to do it is with Ajax.

You can use JQuery framework to make the call to the server. This is pretty interesting if you need to get Html loaded with Model information from the server. A simple way to do it, without having to use parameters is to simply call a partial view with the routing url to the information you want.

For example, let say you want to

var ajaxCall = $.ajax(
  {
    url: 'MyController/MyAction/' + id,
    success: /*...*/, dataType: "html"
  });

This will call the server, get the information of the id and render the html for it.

In the success fonction, you just have to setup with .html(contentHere) and you will be fine to load the data from the Model of the server into the html without having to do a request with a PostBack.

One important note is that the controller need to return a PartialView and not simply a View. This would cause to load the whole layout back to the client and it's not what you should want.