【问题标题】:Is there any way to provide the contents of a Razor view from a string variable rather than from a file?有没有办法从字符串变量而不是文件提供 Razor 视图的内容?
【发布时间】:2014-02-07 13:58:00
【问题描述】:

例子--

var myView = "<p>The date is @DateTime.Now.ToLongDateString()</p>";
return View(myView);

本质上,我想覆盖在文件系统上查找视图的 MVC 视图解析功能。我不想从文件中读取 Razor 代码,而是将其作为字符串提供。

(为什么?所以我可以在单独的 DLL 中编译视图并将它们放入项目中。如果我的做法完全错误,请告诉我。)

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-4 razor views


【解决方案1】:

Controller 类有一个名为 content 的方法,它返回 ContentResult

在你的行动中你可以像Content("your string content");一样使用它

你可以对你的内容进行配置

        // Summary:
        //     Gets or sets the content.
        //
        // Returns:
        //     The content.
        public string Content { get; set; }
        //
        // Summary:
        //     Gets or sets the content encoding.
        //
        // Returns:
        //     The content encoding.
        public Encoding ContentEncoding { get; set; }
        //
        // Summary:
        //     Gets or sets the type of the content.
        //
        // Returns:
        //     The type of the content.
        public string ContentType { get; set; }

【讨论】:

    【解决方案2】:

    您可以使用RazorEngine 从字符串中解析 Razor:

        string result = RazorEngine.Razor.Parse("<p>The date is @DateTime.Now.ToLongDateString()</p>");
        return Content(result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多