asp.net-mvc - Razor 。 ASP.NET MVC 3.动态创建页面/内容

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

对我来说,问题是了解当页面没有要映射的 Controller / View 时如何使用唯一 URL 渲染动态创建的页面。

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

我想我需要在 Controller 中进行一些渲染操作,以使用数据库中的内容创建自定义 View ? URL 又如何呢?

最佳答案

我会创建一个单独的文件夹(例如“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%

更新

如果您不想将文件放置在服务器硬盘上,那么您实际上可以为这些文件创建一个特殊的 Controller 。此路线应如下所示:

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 方法。

关于asp.net-mvc - Razor 。 ASP.NET MVC 3.动态创建页面/内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8923134/

相关文章:

asp.net-mvc - 为什么不带参数的POST不返回JSON

ASP.NET MVC : How to use static HTML pages in MVC applications?

asp.net-mvc-3 - 使用 MVC HTML 助手(如 ActionLink、BeginForm、TextBox 等)代替原生 HTML 标签有什么好处?

c# - razor 中可以使用哪些 c# 类和函数?

c# - 在javascript中访问cs变量

c# - 首先在 Entity Framework 数据库中级联删除

asp.net-mvc - IIS 压缩模块和 Vary : Accept-Encoding Header

asp.net-mvc-3 - 使用t4脚手架在mvc4中获取模型(TableName)的元数据

asp.net-mvc-3 - MVC3 强类型局部 View 模型绑定(bind)

c# - 在 Razor 和 MVC 中为表创建提交按钮