2016-08-22 76 views
0

我怎麼能映射以下網址...如何將字符串傳遞給我的控制器行動

domain.com/Products/product-name-here

我想這個映射到我的GetProduct行動在我的產品控制器上。

以下是我在我的route.config

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

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

      routes.MapRoute(
       name: "Product", 
       url: "product/{id}" 
      ); 

      routes.MapRoute(
       name: "EditProduct", 
       url:"Admin/Product/{action}", 
       defaults: new { controller = "Products", action = "Index"} 
      ); 

      routes.MapRoute(
       name:"ProductPages", 
       url:"Products/{id}", 
       defaults: new {controller = "Products", action = "GetProduct", id = UrlParameter.Optional } 
      ); 

      routes.MapRoute(
       name:"OrderRoute", 
       url:"Orders/", 
       defaults: new { controller= "Order", action="Index"} 
       ); 
     } 

這裏是我的行動,我希望映射到的路由。

[HttpGet] 
     public ActionResult GetProduct(string pageURL) 
     { 

      if (string.IsNullOrWhiteSpace(pageURL))    
          return View("PageNotFound"); 


      var product = db.Products.Where(x => x.PageURL == pageURL); 

      return View("GetProduct"); 

     } 

回答

1

地址:

routes.MapRoute(
    name:"ProductPages", 
    url:"Products/{pageURL}", 
    defaults: new {controller = "Products", action = "GetProduct" } 
); 

重要提示:您的默認路由應該是您的route.config中的最後一個路由。 在你的代碼中它是第一個。

編輯:您的實際路線「ProductPages」應該被刪除或編輯,以避免與我的建議衝突。

+0

這爲我工作。謝謝! – ddeamaral

0

此代碼實際上並不調用一個動作:

routes.MapRoute(
       name:"ProductPages", 
       url:"Products/{id}", 
       defaults: new {controller = "Products", action = "GetProduct", id = UrlParameter.Optional } 
      ); 

你想添加使用的行爲,像這樣的路徑(注意動作標籤):

routes.MapRoute(
       name:"ProductPages", 
       url:"Products/{action}/{id}", 
       defaults: new {controller = "Products", action = "GetProduct", id = UrlParameter.Optional } 
      ); 
相關問題