2/13/12

Some useful MVC grub

Changing the view name via the OnActionExecuted handler

Let us say there is an action method as shown below:


[ChangeViewFilter]
public ActionResult GetTeamDetails(string teamName)
{

 return View("DallasCowboys");

}

This method takes one input parameter called "teamName" and returns a view called "DallasCowboys".As you can see, the method is also decorated with a custom filter called "ChangeViewFilter".

The purpose of this filter is to change the View Name in the ActionResult of the GetTeamDetails method,if a certain condition X is satisfied. So if the condition X is satisfied we will change the View Name to "HoustonTexans" else we do nothing(the name remains "DallasCowboys").

We achieve this by overriding the OnActionExecuted method of the MVC framework that gets called after the GetTeamDetails gets called and before the View Engine is invoked. The code is as follows:


public class ChangeViewFilterAttribute : ActionFilterAttribute
 {
  public override void OnActionExecuted(ActionExecutedContext context)
    {
        //get the current view name
        string ViewName = ((ViewResultBase)(context.Result)).ViewName;

        //if the view name is not specified
     //it means the view name is the same as the action method name
        if (string.IsNullOrEmpty(ViewName))
            ViewName = context.ActionDescriptor.ActionName;

       if(ConditionX)
        ((ViewResultBase)(context.Result)).ViewName = "HoustonTexans";
    }
 }

No comments: