Search code examples
asp.net-mvcrouteswizardmaproute

ASP.Net MVC: Map route according to parameter value


I'm trying to create a wizard-like workflow on a site, and I have a model for each one of the steps.

I have the following action methods:

public ActionResult Create();
public ActionResult Create01(Model01 m);
public ActionResult Create02(Model02 m);
public ActionResult Create03(Model03 m);

And I want the user to see the address as

/Element/Create
/Element/Create?Step=1
/Element/Create?Step=2
/Element/Create?Step=3

All the model classes inherit from a BaseModel that has a Step property. The action methods that have the parameters have the correct AcceptVerbs constraint.

I tried naming all the methods Create, but that resulted in a AmbiguousMatchException.

What I want to do now is to create a custom route for each one of the actions, but I can't figure out how to do it. This is what I tried:

     routes.MapRoute(
        "ElementsCreation", 
        "Element/Create",
        new{controller="Element", action="Create01"},
        new{Step="1"}
        );

But this doesn't work.

Any help (on the correct MapRoute call or maybe a different approach) would be greatly appreciated.

Thanks


Solution

  • I actually found a different approach.

    Instead of adding a new Route Map, I created a new Action Method attribute to verify if the passed request is valid for each of the action methods.

    This is the attribute class:

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class ParameterValueMatchAttribute : ActionMethodSelectorAttribute
    {
       public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
       {
          var value = controllerContext.RequestContext.HttpContext.Request[Name];
          return (value == Value);
       }
    
       public string Value { get; set; }
       public string Name { get; set; }
    }
    

    And I have each one of the action methods with the same name and decorated like this:

    [AcceptVerbs(HttpVerbs.Post)]
    [ParameterValueMatch(Name="Step", Value="1")]
    public ActionResult Create(Model01 model)
    

    I like this approach a LOT more than creating one route for each method.