Yves
Yves

Reputation: 3902

How to check if action result is partial view or view?

Is there any way to find out on client side what kind of action was executed? I just want to know if view is generated by PartialView method or View method.

I looked in headers but found nothing useful. To achieve this I may add some headers into http response by overriding PartialView method.

protected override PartialViewResult PartialView(string viewName, object model)
{
    Response.AddHeader("is-partial", "of_course_this_is_partial");
    return base.PartialView(viewName, model);
}

But I want to know is there any built in solution in MVC 5? So I won't have to use a custom derived Controller class and use it everywhere.

Upvotes: 1

Views: 3235

Answers (1)

L-Four
L-Four

Reputation: 13531

You could use an action filter:

public class ResponseHeaderActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {

    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        // use filterContext.Result to see whether it's a partial or not
        // filterContext.HttpContext.Response.AddHeader().. 
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {

    }        
}

If you make this a global action filter, it's automatically executed and you don't have to inherit from a base controller or put it as an attribute on your controller:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    // Register global filter
    GlobalFilters.Filters.Add(new ResponseHeaderActionFilter());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

This way, the header is automatically added to each result.

Upvotes: 1

Related Questions