Share MVC PartialView between server and client

In MVC you can divide a big view into smaller partial views, while with ajax these partial views can also be used by ajax to do partial update of an already rendered page.

In the partial view you can put server rendering scripts by using Html helper, or just client side scripts like html and javascript, it makes no difference this shared partial view is used by a containing mvc server view or called by an ajax request through an action in controller

Here I am going to give you an example of how to call a partial server view and shove it into a div through ajax.

1. Create a parital view under Views folder, let us say it is Template.cshtml

2. Create an action in your controller to handle ajax GET

[HttpGet]
public ActionResult Template()
{
  return PartialView();
}

You do not have to give the view name here if it has the same name with your action name.

3. on client side,javascript

  $.ajax({
        type: "GET",
        url:'@Url.Action("Template","ControllerName")' ,
        success: function (result) {
        // result is your rendered partial view
          $('#editpanel').append(result);
        }
  });

In this way you do not need to write a view twice if it is used by server view in the page rendering process and used by ajax after the page is rendered.

The example shows how to define the action to handle ajax call and the consumption of it using jquery.ajax get, do not set datatype to Json as you normally do because the partial view actually returned as an html string. The same reason the action returns ActionResult rather than a JsonResult.

Tags:

This entry was posted on Tuesday, November 20th, 2012 at 10:46 pm and is filed under ASP.NET. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

*