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?
Just specify externalstring parameter on your action method: public ActionResult Index(string externalstring) { // ... } Or you can use Request. QueryString property.
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.
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.
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
}
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With