2/13/12

Some more useful MVC grub

Assigning values to Action method parameters via OnActionExecuting handler

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


[SetParameterValueFilter]
public ActionResult GetCityDetails([Bind(Prefix="MyCity")]string cityName)
{

 return View();

}


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

The purpose of this filter is to assign a value to the input parameter "cityName" of the action method GetCityDetails based on a certain condition X. So if the condition X is satisfied we will set the parameter value to "Dallas" else we will set it to "Houston".

We achieve this by overriding the OnActionExecuting method of the MVC framework that gets called before the GetCityDetails method gets called.

The code is as follows:


public class SetParameterValueFilterAttribute : ActionFilterAttribute
{  
   public override void OnActionExecuting(ActionExecutingContext context)
   {
     ParameterDescriptor[] ActionMethodParams = context.ActionDescriptor.GetParameters();

    //get the parameter that has a prefix 
    //of "MyCity" and set the value
     foreach (var param in ActionMethodParams)
     {
      if (param.BindingInfo.Prefix.ToUpper() == "MYCITY")
       {
          //set the parameter value
        if(ConditionX)
          context.ActionParameters[param.ParameterName] = "Dallas";
        else
          context.ActionParameters[param.ParameterName] = "Houston";
        break;
       }
     }
  }   
}

No comments: