Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map querystring to action method parameters in MVC?

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?

like image 834
LP13 Avatar asked Jan 31 '17 23:01

LP13


People also ask

How can get QueryString value in MVC controller?

Just specify externalstring parameter on your action method: public ActionResult Index(string externalstring) { // ... } Or you can use Request. QueryString property.

How do I pass QueryString?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.

What is action parameters in MVC?

Action Method Parameters are most important in MVC. If you want to handle post request in action methods; MVC framework provided types of Action Methods Parameters. Action Method Parameters. We can organize the action methods for GET and POST requests separately.


1 Answers

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
}
like image 94
Win Avatar answered Sep 22 '22 05:09

Win