How can i route to different actions having same signature if i don't want to display action name in URL?
I am having one controller Test having following actions
public ActionResult ABC (string parameter1, string parameter2)
public ActionResult XYZ (string parameter1, string parameter2,string parameter3, string parameter4)
i have added following html.routelinks
<%= Html.RouteLink("ABC","ABC", new { parameter1 = 100, parameter2 = 200 } )%><br />
<%= Html.RouteLink("XYZ", "XYZ", new { parameter1 = 1000 , parameter2 = 2000 }) %>
last two parameters in XYZ action are optionals so i have omitted them in Html.routelink
routes.MapRoute("ABC", "Test/{parameter1}{parameter2}", new { controller = "Test", action = "ABC", parameter1= 0,parameter2=0 });
routes.MapRoute("XYZ", "Test/{parameter1}{parameter2}{parameter3}{parameter4}",开发者_运维知识库 new { controller = "Test", action = "XYZ", parameter1=0,parameter2=0 ,parameter3=UrlParameter.Optional,parameter4=UrlParameter.Optional});
In above senario in both cases same route "ABC" is called eventhough i have clicked on second Html.routelink. can anyone solve this issue ? how can i route according to route name instead of number of parameters?
First you need to separate the route parameters with /
or you will get a runtime error:
routes.MapRoute("ABC", "Test/{parameter1}/{parameter2}",
new {
controller = "Test",
action = "ABC",
parameter1 = 0,
parameter2 = 0
}
);
routes.MapRoute("XYZ", "Test/{parameter1}/{parameter2}/{parameter3}/{parameter4}",
new {
controller = "Test",
action = "XYZ",
parameter1 = 0,
parameter2 = 0,
parameter3 = UrlParameter.Optional,
parameter4 = UrlParameter.Optional
}
);
Then when you are generating the two links you are specifying the same parameters: parameter1
and parameter2
and as you haven't specified any action part in your routes there's no way to disambiguate between those two. The routing engine cannot know which action to call and so it simply picks the first route in the route definition (that's why the order is important). If you specify different parameters then it will work:
<%= Html.RouteLink("ABC","ABC", new { parameter1 = 100, parameter2 = 200 } )%>
<br />
<%= Html.RouteLink("XYZ", "XYZ", new { parameter3 = 1000 , parameter4 = 2000 }) %>
精彩评论