Reputation: 73
How does one remove the Layout property of a view from a view on IResultFilter.OnResultExecuting
?
EDIT:
I'm trying to remove the layout if the request is from AJAX. The following isn't working for me:
public class RemoveLayoutIfRequestIsFromAjaxResultFilterAttribute : ResultFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext context)
{
if (!(context.Result is ViewResult viewResult))
return;
if (context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
viewResult.ViewData["Layout"] = "";
}
else
{
viewResult.ViewData["Layout"] = "_Layout";
}
}
}
I also tried the OnResultExecuting
method with no success.
Upvotes: 0
Views: 199
Reputation: 5031
Layout is set through ViewData
, you can change the layout of the current view through
the ViewData["Layout"]
of ViewResult
.
Remove the layout by setting its value to empty.
public class ViewLayoutAttribute : ResultFilterAttribute
{
public ViewLayoutAttribute()
{
}
public override void OnResultExecuting(ResultExecutingContext context)
{
var viewResult = context.Result as ViewResult;
if (viewResult != null)
{
viewResult.ViewData["Layout"] = "";
}
}
}
Controller
[ViewLayout]
public IActionResult Index()
{
return View();
}
Note: If the layout has been set in the current view, such as:
@{
Layout = "_Layout2";
}
The view will give priority to the layout(_Layout2) set by the current view.
Upvotes: 1