2013-04-25 55 views
-1

我最近問了一個基於如何基於內容表創建頁面的問題,其中包含以下內容:標題內容。我按照我的理解,在answer that was given之後。我的路線和行爲有什麼問題?

我創建像這樣的路線:

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

     routes.MapRoute(
      "Default", // Route name 
      "{controller}/{action}/{id}", // URL with parameters 
      new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
     ); 

     routes.MapRoute(
      "ContentManagement", 
      "{title}", 
      new { controller = "ContentManagement", action = "Index", title = "{title}" } 
     ); 

    } 

我假設我可以做這樣的路線?我可以在哪裏設置多條路線?我還假設我可以像我所做的那樣將標題傳遞給控制器​​操作?從我創建了一個索引作用的控制器,看起來這樣的

namespace LocApp.Models 
{ 
    public class ContentManagement 
    { 
     public int id { get; set; } 
     [Required] 
     public string title { get; set; } 
     public string content { get; set; } 
    } 
} 

public ViewResult Index(string title) 
    { 
     using (var db = new LocAppContext()) 
     { 
      var content = (from c in db.Contents 
          where c.title == title 
          select c).ToList(); 

      return View(content); 

     } 
    } 

於是我創造了一些內容與冠軍

然後我創建的模型「bla」,所以當我訪問site.com/bla我得到一個錯誤,它不能找到「bla /」

有人可以告訴我我在做什麼G?如果您熟悉頂部選項卡的asp.net mvc項目的默認佈局,我也會這樣做,根據數據庫中的標題創建一組導入頁面的選項卡

+0

見http://stackoverflow.com/questions/13558541/what-kind-of-route-would-i-need-to-provide-vanity-urls?rq=1。 – 2013-04-25 16:24:01

回答

1

主要問題在於,當您使用標題時,路由引擎會將其與第一條路線匹配,並嘗試通過該標題找到控制器。我們已經實現了類似的東西,發現通過明確定義哪些控制器對默認路由有效,然後它會適當地處理請求。我舉了一個我們允許的控制器的例子來適應我們的默認路線(Home,Help和Error)。

您可能還想阻止人們將內容作爲根級別控制器提供相同的標題,因爲這樣會很好地解決此問題。

public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
routes.MapRoute(
       "Default", 
       "{controller}/{action}/{id}", 
       new {controller = "Home", action = "Index", id = UrlParameter.Optional}, 
       new {controller = "Home|Error|Help"}, 
       new[] {"UI_WWW.Controllers"}); 

      routes.MapRoute(
       "ContentManagement", 
       "{title}", 
       new {controller = "ContentManagement", action = "Index"});  

      } 
}