Asp.Net Routing with different parameter names
I'm trying to map certain routes so that auto generated Urls will look like
Admin/controller/action/param
for both of these code blocks,
@Url.Action("action","controller",new{id="param"})
and
@Url.Action("action","controller",new{type="param"})
What I did was th开发者_StackOverflowe following in the area registration,
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index",
id = UrlParameter.Optional },
new string[] { "namespaces" });
context.MapRoute(
"Admin_type",
"Admin/{controller}/{action}/{type}",
new { action = "Index",
type = UrlParameter.Optional },
new string[] { "namespaces" });
when parameter name is id
, url generated is as expected, but when parameter name is type
, instead of controller/action/typevalue
, it generates something like controller/action/?type=typevalue
Is there a way to generate the url something like controller/action/typevalue
keeping the generator behaviour for Admin_default
route intact?
when parameter name is id, url generated is as expected, but when parameter name is type, instead of controller/action/typevalue, it generates something like controller/action/?type=typevalue
That happens because first route is used to map the url (id is optional).
You could try adding some constraints to your routes. I'm guessing your id parameter is an integer and type parameter is a string. In that case you can try with this routes:
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new { id = @"\d+" },
new string[] { "namespaces" });
context.MapRoute(
"Admin_type",
"Admin/{controller}/{action}/{type}",
new { action = "Index", type = UrlParameter.Optional },
new string[] { "namespaces" });
You can find more info on route constraints here.
Have you tried removing the Optional default value on id ? In this case, the first route shouldn't match when providing only the type parameter.
EDIT: After reading again your question, my solution doesn't keep your first route intact ...
You only need the one route.
context.MapRoute("Admin_default",
"Admin/{action}/{id}",
new { action = "Index",
id = UrlParameter.Optional },
new string[] { "namespaces" });
in your controller you
URLs: http://website/Admin/index/hello
http://website/Admin/type/342
public class AdminController()
{
public ActionResult Index(string id)
{
// do whatever
returne View();
}
public ActionResult type(string id)
{
// do whatever
returne View();
}
}
精彩评论