I'm trying to figure out how I can automatically render a view as a partial (no master page) when the request is made through ajax.
What I want to avoid is to use the following code in every controller method that can return ajax (since that's not very DRY):
return Request.IsAjaxRequest() ? PartialView(model) : View(model)
My first thought was to add the check into my base controller in the View
method. But the view method returns a View
(which PartialView
do not inherit). So that failed.
My next attempt was to try to make the check in my custom razor view engine and simple remove the master page if it's a ajax request. But that failed too.
What I can do is to create a new method ViewOrPartial
which contains the check and return a result accordingly.
How would you have done it?
How about putting the following:
@{
Layout = !Request.IsAjaxRequest() ? "~/Views/Shared/_Layout.cshtml" : null;
}
in your ~/Views/_ViewStart.cshtml
and in your controller action simply returning a view:
return View(model);
All razor views use _ViewStart.cshtml
. This is where the master page is specified. So by making this change all views automatically will apply the master page only conditionally if the request was not an AJAX request. Pretty DRY.