Reputation: 2878
Is there any way to set the view file name as an attribute on top of Action ?
ex:
[ViewName("~/Views/CustomerInformation.cshtml")]
public ActionResult ViewCustomers()
{
//
}
purpose is to change the view file dynamically at run time.
Upvotes: 2
Views: 1839
Reputation: 1038710
Of course, you could override the OnActionExecuted
method and replace the original view name that was used by the one specified in the action filter:
public class ViewNameAttribute : ActionFilterAttribute
{
private readonly string _viewName;
public ViewNameAttribute(string viewName)
{
_viewName = viewName;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var result = filterContext.Result as ViewResultBase;
if (result != null)
{
result.ViewName = _viewName;
}
}
}
and then you could just return a dummy view:
[ViewName("~/Views/CustomerInformation.cshtml")]
public ActionResult ViewCustomers()
{
return View();
}
But I wonder what the practical application of your custom action filter is when you could directly write:
public ActionResult ViewCustomers()
{
return View("~/Views/CustomerInformation.cshtml");
}
You doesn't seem to be bringing much value with this custom action filter to what the framework already provides.
Upvotes: 4