剃刀。 ASP.NET MVC 3.动态创建页面/内容

时间:2012-01-19 08:39:50

标签: asp.net-mvc asp.net-mvc-3 razor

我的问题是了解当页面没有要映射的控制器/视图时,如何使用uniq URL呈现动态创建的页面。

我正在使用Razor在ASP.NET MVC 3 3中构建CMS系统。在数据库中,我存储页面/站点结构和内容。

我想我需要在控制器中进行一些渲染操作,使用数据库中的内容创建自定义视图?那URL是什么?

2 个答案:

答案 0 :(得分:2)

我创建了一个单独的文件夹(比如“DynamicContent”或其他东西)来保存这些动态页面,并在Global.asax.cs中向RegisterRoutes方法添加相应的IgnoreRoute调用,如下所示:

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

    ...
}

之后,用户将能够使用

等URL访问这些页面

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

<强>更新

如果您不想在服务器硬盘上放置文件,那么您可能真的为这些文件创建了一个特殊的控制器。这个的路线应该是这样的:

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之后抓取整个网址部分 - 所以如果您输入了http://%your_site%/Dynamic/path/to/file/something.html,那么整个字符串path/to/file/something.html将在参数中传递pathInfo到DynamicController / Index方法。

答案 1 :(得分:1)

您可以使用Visual Studio社区版,您可以从此处下载它,它还可以生成动态网站的所有URL https://visual-seo.com/

相关问题