2

I know you can pass in parameters via urls like .com/MyPage/?controlID=5 but how can you do it with something like .com/MyPage/5? Thus not requiring the variable name or a question mark.

2 Answers 2

5

You would define a custom route, or use the model binding to get the intended effect. In your case, the route would be something like:

routes.Add("someRoute",
    "{controller}/{action}/{controlId}",
    new { controller = "Home", action = "Index", controlId = UrlParameter.Optional }
    );

public ActionResult Index(int? controlId)
{
}

Now, the only "gotcha" with this route is that if you also have the default route specified, these two routes will be in contention and the first one you have defined will win. If there is some form of differentiating value (say, that controlId always matches some kind of pattern), then you can always add a HttpRouteConstraint to the route to differentiate your new route from the default route.

Alternatively, you can rename the parameter on your action method, if you are still using the default route, to be id, and change your query string key to 'id':

public ActionResult Index(int? id)
{
   // Do Stuff
}
Sign up to request clarification or add additional context in comments.

3 Comments

This worked perfectly, you were very thorough and clear, thank you very much!
Is there a way I can set the HttpRouteConstraint to determine between something like an int or string, or does it have to be something like "POST" or "GET"?
Sure - check out this article to see how to make a constraint.
2

Create a method in MyPageController:

public ActionResult Index (int id)
{
}

That will work with the default routes

1 Comment

I tried that and it worked, but only for the way that requires the input of a variable name and question mark, is it possible to do it without those?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.