1

Suppose I have defined route like that,

        context.MapRoute(
            "Preview",
            "/preview/{id}/{type}",
            new { controller = "Preview", action = "Invoice", id = UrlParameter.Optional, type = UrlParameter.Optional }
        );

I have controller with action Invoice

public ActionResult(int id, string type)
{
  if (type == "someType") 
  {
    // ...
  } 
  else
  {
    // ..
  }
}

I want to get rid of If-Else case inside the action. Is it possible to attribute action somehow, so ASP.MVC would distinguish between both, like:

Just a pseudocode tho show idea?

[HttpGet, ActionName("Action"), ForParameter("type", "someType")]
public ActionResult PreviewSomeType(int id) {}

[HttpGet, ActionName("Action"), ForParameter("type", "someType2")]
public ActionResult PreviewSomeType2(int id) {}

Is something like that possible in MVC2/3 ?

2 Answers 2

4

Action method selector

What you need is an Action Method Selector that does exactly what you're describing and are used exactly for this purpose so that's not a kind of a workaround as it would be with a different routing definition or any other way. Custom action method selector attribute is the solution not a workaround.

I've written two blog posts that will get you started with action method selection in Asp.net MVC and these kind of attributes:

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I think Action Method Selector is very applicable!
0

I think thats what routing is for. Just split your single route into two:

context.MapRoute(null, "preview/{id}/SomeType",
        new { 
              controller = "Preview", 
              action = "Action1", 
              id = UrlParameter.Optional, 
            }
    );

context.MapRoute(null, "preview/{id}/SomeOtherType",
        new { controller = "Preview", 
              action = "Action2", 
              id = UrlParameter.Optional, 
            }
    );

Or maybe more general, use the last segment as the action name:

context.MapRoute(null, "preview/{id}/{action}",
        new { controller = "Preview",
              id = UrlParameter.Optional, 
            }
    );

But i think, optional segments have to appear at the end. So why don't you use the default routing schema

controller/action/id

?

2 Comments

thanks, but I would be happy to avoid several routes definitions;
but, I would agree with 3 option - general one :) meanwhile I fould that possiblity msdn.microsoft.com/en-us/library/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.