MVC Link Creation
Using this route:
routes.MapRoute(
"PartListRoute",
"Products/PartList/{Manufacturer}/{Product}/{PartNumber}",
开发者_C百科 new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional, Product = UrlParameter.Optional, PartNumber = "" }
);
I am attempting to create a link going from /Products/PartList to /Products/PartList/Manufacturer1 based on a list of manufacturers pulled from a database. mfr.Name is the name of the manufacturer.
The route should lead to urls like the following
- /Products/PartList/
- /Products/PartList/Manufacturer1/
- /Products/PartList/Manuracturer3/Product1/
- /Products/PartList/Manuracturer2/Product4/DN-438
The closest I've come is
@Html.RouteLink(mfr.Name, "PartListRoute", new { Manufacturer = mfr.Name} )
Which puts the manufacturer name in the text, but does not add it to the URL. I get the feeling I'm assuming something about routes and links that isn't true.
Is there actually way to use the Route to generate a new Link in the correct format?
In case anyone else comes across this question, I finally stumbled across this article, indicating there's a bug when you have consecutive optional URL parameters.
http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx
I won't claim I fully understand the explanation, but creating additional routes all pointing back to the original controller seems to have fixed the problem:
routes.MapRoute(
"PartListRoute",
"Products/PartList/{Manufacturer}",
new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional }
);
routes.MapRoute(
"PartListRoute2",
"Products/PartList/{Manufacturer}/{Product}",
new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional, Product = UrlParameter.Optional }
);
routes.MapRoute(
"PartListRoute3",
"Products/PartList/{Manufacturer}/{Product}/{PartNumber}",
new { controller = "PartList", action = "Index", Manufacturer = UrlParameter.Optional, Product = UrlParameter.Optional, PartNumber = "" }
);
精彩评论