Going into a particular design I want pages to refresh the full context including the assigned layout, but I really want a way to also say “hey, I want to load this page context via AJAX, so don’t give me the page layout please”. I came across a rather easy solution — Inside ASP.NET MVC 3 there is support for a _ViewStart.cshtml file under the Views/ directory. This page is loaded for every View you use by default and usually specifies a single Layout page to use.
This is great for a few reasons
- There is no need to specify a Layout page on every view assuming it is the same as specified inside the _ViewStart.cshtml file.
- We can put view conditions in there for mobile layouts, etc.
- We can check the information sent to the server (QueryString from the URL, Form, Cookies and ServerVariables)
I chose to include a variable in the URL called “ajax” which lets me tell the site to turn a full page into the partial page content I really want.
I will say you can explicitly bypass the _ViewStart.cshtml page by rendering a PartialView() and returning a PartialViewResult in the Action, but this is extra work if you need the option for the full view and partial with no changes.
Original Views\_ViewStart.cshtml file:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Modified Views\_ViewStart.cshtml file:
@{
if (!Request.QueryString["ajax"].IsEmpty())
{
Layout = null;
}
else
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
I hope you find this useful and as always if you have any suggestions or enhancements to this idea please let me know.