MVC 3: How to render a view without its layout page when loaded via ajax?
In ~/Views/ViewStart.cshtml
:
@{
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}
and in the controller:
public ActionResult Index()
{
return View();
}
I prefer, and use, your #1 option. I don't like #2 because to me View()
implies you are returning an entire page. It should be a fully fleshed out and valid HTML page once the view engine is done with it. PartialView()
was created to return arbitrary chunks of HTML.
I don't think it's a big deal to have a view that just calls a partial. It's still DRY, and allows you to use the logic of the partial in two scenarios.
Many people dislike fragmenting their action's call paths with Request.IsAjaxRequest()
, and I can appreciate that. But IMO, if all you are doing is deciding whether to call View()
or PartialView()
then the branch is not a big deal and is easy to maintain (and test). If you find yourself using IsAjaxRequest()
to determine large portions of how your action plays out, then making a separate AJAX action is probably better.
Just put the following code on the top of the page
@{
Layout = "";
}