8

I have a url http://localhost/Home/DomSomething?t=123&s=TX and i want to route this URL to the following action method

public class HomeController
{
   public ActionResult DoSomething(int taxYear,string state)
   {
      // do something here
   }
}

since the query string names does not match with action method's parameter name, request is not routing to the action method.

If i change the url (just for testing) to http://localhost/Home/DomSomething?taxYear=123&state=TX then its working. (But i dont have access to change the request.)

I know there is Route attribute i can apply on the action method and that can map t to taxYear and s to state.

However i am not finding the correct syntax of Route attribute for this mapping, Can someone please help?

4
  • 1
    Why not just public ActionResult DoSomething(int t,string s)? Commented Jan 31, 2017 at 23:04
  • 1
    You can always use Request.QueryString["t"]; inside your controller action Commented Jan 31, 2017 at 23:08
  • If you can change the Action's parameter names then you should just do as Stephen Muecke suggested and change the names to match the query string names Commented Jan 31, 2017 at 23:12
  • The query string has absolutely nothing at all to do with (built-in) routing. The MVC framework uses value providers to supply query string information to the MVC pipeline. You can change its behavior by creating your own value provider. See this similar question. Commented Feb 1, 2017 at 9:21

1 Answer 1

17

Option 1

If Query String parameters are always t and s, then you can use Prefix. Note that it won't accept taxYear and state anymore.

http://localhost:10096/home/DoSomething?t=123&s=TX

public ActionResult DoSomething([Bind(Prefix = "t")] int taxYear, 
   [Bind(Prefix = "s")] string state)
{
    // do something here
}

Option 2

If you want to accept both URLs, then declare all parameters, and manually check which parameter has value -

http://localhost:10096/home/DoSomething?t=123&s=TX
http://localhost:10096/home/DoSomething?taxYear=123&state=TX

public ActionResult DoSomething(
    int? t = null, int? taxYear = null, string s = "",  string state = "")
{
    // do something here
}

Option 3

If you don't mind using third party package, you can use ActionParameterAlias. It accepts both URLs.

http://localhost:10096/home/DoSomething?t=123&s=TX
http://localhost:10096/home/DoSomething?taxYear=123&state=TX

[ParameterAlias("taxYear", "t")]
[ParameterAlias("state", "s")]
public ActionResult DoSomething(int taxYear, string state)
{
    // do something here
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.