Search code examples
c#asp.netasp.net-mvcaction-filter

ASP.NET MVC: How to access View Name in a Action Filter


I have written below Action Filter for model validation-

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var viewData = filterContext.Controller.ViewData;
        var viewNme = filterContext.Controller;
        if (!viewData.ModelState.IsValid)
        {
            filterContext.Result = new ViewResult
            {
                ViewData = viewData,
                ViewName = "Test"

            };
        }
        base.OnActionExecuting(filterContext);
    }

if I do not pass ViewName = "WhitePaper" It fails with below message - Server Error in '/Travelers.eBusiness.Travelers.Web' Application.

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

My question is - How do I pass view info ?


Solution

  • You can get the result's view name on the OnActionExecuted event.

    This should give you the view name.

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {       
        var viewData = filterContext.Controller.ViewData;
        var view = filterContext.Result as ViewResultBase;
        if (view != null)
        {
            string viewName = view.ViewName;
            // If we did not explicitly specify the view name in View() method,
            // it will be same as the action name. So let's get that.
            if (String.IsNullOrEmpty(viewName))
            {
                viewName = filterContext.ActionDescriptor.ActionName;
            }
            // Do something with the viewName now
    
        }
    }
    

    filterContext.Controller.ViewData will be available (not null) after the action method got executed. But if you want this in the OnActionExecuting event, you might consider reading the action name and use that ( Assuming your action method is returning a view without explcitly specifying a view name.)

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       var actionMethodName = filterContext.ActionDescriptor.ActionName;
       // This will be same as your view name if you are not explicitly
       // specifying a different view name in the `return View()` call
    
    }