I've been working on a large MVC application over the past month or so, but this is the first time I've ever needed to define a custom route handler, and I'm running into some problems. Basically I have two parameters to pass. The first one is required and the second one is optional.
I'm following this answer here.
Here is my custom route:
routes.MapRoute(
"MyRoute",
"{controller}/{action}/{param1}/{param2}",
new {
controller = "MyController",
action = "MyAction",
param1 = "",
param2 = "" // I have also tried "UrlParameter.Optional" here.
}
);
And my action method signature:
public ActionResult MyAction(string param1, string param2)
If I try the URL http://[myserver]/MyController/MyAction/Test1/Test2
then it works like I expect it to, with param1 = "Test1" and param2 = "Test2"
If I try the URL http://[myserver]/MyController/MyAction/Test1
then both parameters are null.
Hopefully somebody can tell me what I'm doing wrong here, because I'm lost.
You can make a URI parameter as optional by adding a question mark (“?”) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.
Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.
The three segments of a default route contain the Controller, Action and Id.
We can make a route parameter optional by adding “?” to it. The only gimmick is while declaring a route parameter as optional, we must specify a consequent default value for it: [HttpGet("GetById/{id?}")]
Try this
routes.MapRoute("MyRoute",
"myRoute/{param1 }/{param2 }",
new { controller = "MyController", action = "MyAction", param2 = UrlParameter.Optional },
new { param2 = @"\w+" });
you can specify one parameter as optional by using "UrlParameter.Optional" and specified second one with DataType means if you pass integer value then DataType (@"\d+") and for string i have mention above.
NOTE: Sequence of parameter is very important Optional parameter must pass at last and register your new route Before Default Route In Gloab.asax.
then you action link like
<a href="@Url.RouteUrl("MyRoute", new { param2 = "Test1",param1 = "Test2"})">Test</a>
OR with one parameter
<a href="@Url.RouteUrl("MyRoute", new { param2 = "Test1"})">Test</a>
In you Controller
public ActionResult MyAction(string param2,string param1)
{
return View()
}
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