How to map querystring to action method parameters in MVC?

只谈情不闲聊 提交于 2020-01-14 09:42:06

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/41969112/how-to-map-querystring-to-action-method-parameters-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!