Saturday, 16 July 2011

Asp.net MVC 3 / Razor – Using the same view through regular action and Ajax loading

Ever had a view which you wanted to reuse and load through a regular action call or through using the action using a JavaScript call but then it loads in the associated layout multiple times? I had this exact issue recently.

And the solution; in the _ViewStart.cshtml file which specifies the default layout replace:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

with

@{
    Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}

Then in the controllers actions they still continue to return the same view but don’t have any layout associated to it. This could be used to add a specific “ajax” layout instead of none.

Sample project can be found on github.