2012-01-19 217 views
2

對於我來說,問題在於瞭解如何在頁面沒有要映射的控制器/視圖時使用uniq URL呈現動態創建的頁面。剃刀。 ASP.NET MVC 3.動態創建頁面/內容

我在使用Razor在ASP.NET MVC 3 3中構建CMS系統。在數據庫中,我存儲頁面/網站結構和內容。

我想我需要在控制器中使用數據庫中的內容創建自定義視圖的一些渲染操作?那麼URL呢?

回答

2

我會成爲一個單獨的文件夾(如「DynamicContent類」或東西),以確保這些動態頁面,並添加相應的IgnoreRoute調用的RegisterRoutes方法Global.asax.cs中,像這樣的:

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

    ... 
} 

之後,用戶將能夠訪問使用URL這些頁面就像

http://%your_site%/DynamicContent/%path_to_specific_file%

UPDATE

如果你不想在服務器硬盤上放置文件,那麼你真的可以爲這些文件創建一個特殊的控制器。路線爲這個應該是這樣的:

public static void RegisterRoutes(RouteCollection routes) 
{ 
    ... 

    routes.MapRoute(
     "DynamicRoute", // Route name 
     "Dynamic/{*pathInfo}", // URL with parameters 
     new { controller = "Dynamic", action = "Index"} // Parameter defaults 
    ); 

} 

你DynamicController.cs應該是這樣的:

public class DynamicController : Controller 
{ 
    public ActionResult Index(string pathInfo) 
    { 
     // use pathInfo value to get content from DB 
     ... 
     // then 
     return new ContentResult { Content = "%HTML/JS/Anything content from database as string here%", ContentType = "%Content type either from database or inferred from file extension%"} 
     // or (for images, document files etc.) 
     return new FileContentResult(%file content from DB as byte[]%, "%filename to show to client user%"); 
    } 
} 

注意,星號(*)之前PATHINFO將Dynamic後使這條路線搶整個URL的一部分 - 所以如果您輸入了http://%your_site%/Dynamic/path/to/file/something.html,則整個字符串path/to/file/something.html將通過參數pathInfo傳遞給DynamicController/Index方法。

+0

感謝您的回答,但如果我是什麼URL來鏡像在數據庫中動態創建的結構。例如:www.mysite.com/about/contact 那麼about和contact就是數據庫中的一個頁面結構。 我希望你明白我的意思? :) –

+0

@Mickjohansson:相應地修改我的答案,希望它有幫助。 –

+0

非常感謝,我現在就試試這個:) –