2012-01-19 147 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

非常感谢,我现在就试试这个:) –