2014-05-11 42 views
0

我有一家網店。我有一些控制器和視圖匹配/管理/索引,/管理/ ShowProducts等所有的東西。如何創建特定的網址路線

我希望能夠做一個「自定義」鏈接,始終是一樣的,它應該是在我的域的根,是這樣的:

www.mydomain.com/shop/myproduct

如果店鋪是靜態的並且沒有變化,並且「我的產品」根據每個產品而變化(它實際上是一個ID)。如何在沒有在默認方式的URL中顯示控制器方法的情況下執行此操作?

這是一條新路線嗎?或者我可以在控制器上做些什麼?

回答

0

默認的MVC路線幾乎已經完成了。

看那控制器=和行動=

因此,讓一個網址,如:

/店/ {ID}

控制器= ShoppingController,行動=店

注意我加假設用戶不必指定產品,並且您得到一些字符串來告訴您這是默認產品,您也可以使用UrlParameter.Optional,並且您將爲ID爲

你的控制器看起來像:

public class ShoppingController : Controller 
{ 
    public ActionResult Shop(string id) 
    { 
     if (string.IsNullOrEmpty(id) || string.Equals(id, "DefaultProduct", StringComparison.OrdinalIgnoreCase)) 
     { 
      // Do something to please the user 
     } 

     // Get product by id 

     return View(); 
    } 
} 

和路由代碼:

public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "Shopping", 
      url: "shop/{id}", 
      defaults: new { controller = "Shopping", action = "Shop" , id = "DefaultProduct" } 
     ); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
    }