Say I have set up a url structure as follows (ASP.NET MVC2)
http://localhost:XXXX/Product/
Click on link browse by color
http://localhost:XXXX/Product/Color/
Click on link browse red color items by type (i.e. pen's)
http://localhost:XXXX/Product/Color/Red/Pen
In the controller, I will need to do a select based on these crit开发者_如何学Pythoneria. Except when previously, I could go
public ActionResult ShowTypesForColor(string color)
but to do this one:
public ActionResult ShowItems(string type)
I also need the color that was selected.
How could I do this? Is splitting up the url string the only way?
edit: maybe i've gotten ahead of myself in the global.asax.cs
routes.MapRoute(null, "Product/Color/", new { controller = "Product", action = "ShowAllColors" });
routes.MapRoute(null, "Product/Color/{color}", new { controller = "Product", action = "ShowTypesForColor" });
routes.MapRoute(null, "Product/Color/{color}/{type}", new { controller = "Product", action = "ShowDetail" });
I don't think I can define the last one like that can I? with two {} values?
Your last route seems perfectly valid. It will map to action with signature like this:
ActionResult ShowDetails(string color, string type) {
return View(/*view params*/);
}
EDIT I think the order is wrong, so if the last route is not being fired, try doing this:
routes.MapRoute(null, "Product/Color/{color}/{type}", new { controller = "Product", action = "ShowDetail" });
routes.MapRoute(null, "Product/Color/{color}", new { controller = "Product", action = "ShowTypesForColor" });
routes.MapRoute(null, "Product/Color/", new { controller = "Product", action = "ShowAllColors" });
The order of MVC routes should be from most specific to least specific, otherwise the least specific route (/product/color/{color}
) will match a url product/color/red/pen
before the more specific /product/color/{color}/{type}
You can put multiple tokens in your route (e.g., {color} and {type}) but it's not going the work the way you have it there. Why have you defined "Color" as the second segment of your URL? Why not just do /Products/Red and /Products/Red/Pen? It's inconsistent to do .../Colors/Red and not .../Types/Pen so I'd just leave the "Colors" and "Types" qualifiers out altogether.
I'd define your ShowItems() method like this:
public ActionResult ShowItems(string color, string type)
this will allow you to have a route like /Products/Red/Pen where your route maps to this ShowItems() method. But you'll still need to differentiate that from the ShowTypesForColor() method where it also takes a first parameter of color. The routing framework will just treat type as null - for the route that has both tokens, make sure you have a route constraint specifying that neither color nor type can be null/empty (i.e., for the ShowItems() route).
精彩评论