简体   繁体   中英

ASP.NET MVC Routing Strange or Unexpected Behavior

I am very new to ASP.NET MVC and am working over an eCommerce application that uses ASP.NET MVC 2.

For all the scenario, the default route works fine. But I need to define my own rule for URL like below:

  1. http: //localhost/mvc2proj/products
  2. http: //localhost/mvc2proj/products/productname

For this, I defined a new route just above the default routing:

 routes.MapRoute(
        "Products", 
        "Products/{productName}",
        new { controller = "Products", action = "Index" }
 );

It works fine when home page gets displayed. That is when the URL is http: //localhost/mvc2proj, the anchor tag's href attribute for menu header "Products" is "href="mvc2proj/Products" Products".

But when the URL is http: //localhost/mvc2proj/products/productname, the anchor tag's href attribute for menu header "Products" also gets changed to href="mvc2proj/Products/productName" which is not obviously desired. The menu href should not be changed whenever Product's category is clicked individually. It should remain unchanged.

I defined menu as a User Control like this:

<li><%=Html.RouteLink("Home", new { Controller = "Main", Action = "Index" })%></li>
<li><%=Html.RouteLink("Products", new{ Controller = "Products" } ) %></li>

Product's subcategory is defined like this:

<%foreach(var product in Model.Products) {%>
    <li><%=Html.RouteLink(Html.Encode(product.ProductName), new { controller = "Products", productName = product.ProductName })%></li>
<%} %>

The HTML for subcategory is:

<li><a href="/mvc2proj/Products/Product1">Product1</a></li>
<li><a href="/mvc2proj/Products/product2">Product2</a></li>

....... and so on. Clicking on these links changes the menu URL.

Please help me.

This may not be the best solution, but I got around a similar issue by defining a different route for the Index page than for the individual product pages, ie something like:

routes.MapRoute(
"ProductIndex", 
"Products",
new { controller = "Products", action = "Index" }
);

This would be additional to your existing route. I think I actually used different Action methods for each, but there would be no need to if you supplied a default value for the parameter.

I am sure there is a better way and that this solution comes from a lack of understanding of what's really going on, but it may help you solve the immediate problem!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM