【问题标题】:Howto render a Func<Object, TemplateWriter> to string in Razor view engine Html Helper?如何在 Razor 视图引擎 Html Helper 中将 Func<Object, Template Writer> 呈现为字符串?
【发布时间】:2011-05-08 07:38:33
【问题描述】:

我实际上并没有使用来自 ASP.NET MVC 的 Razor,我使用的是找到的独立版本 here

我已经按照here 的描述创建了自己的 HtmlHelper

我通过反复试验确定 razor 的 &lt;text&gt; 属性在方法上下文中调用时会生成 Func&lt;Object, TemplateWriter&gt; 对象。

helper 的方法签名如下:

    public String IncludeOnce(Func<Object, TemplateWriter> text) {
       //here I need to be able to render the text Func to a string so
       //I can do some checks, and return it if it hasnt yet been included
       //or return an empty string if it has
    }

我在我的模板中调用它,例如:

    @Html.IncludeOnce(
    @<text>
      <style type="text/css">
        /* styles I only want on the page once, and not everytime the template
           is rendered. Note: I need @Model to work here too*/
        .something { top: @Model.Top }
      </style>
    </text>)

我怎样才能把它作为一个字符串?另外,如果我将它传递给另一个模板,例如:

      public String IncludeOnce(Func<Object, TemplateWriter> text) {
          return Razor.Parse("other.cshtml", new { Content = text(new Object()) })
      }

other.cshtml 在哪里:

      @Model.Content

它有效。 Razor.Parse 知道我不知道什么?

谢谢!

【问题讨论】:

    标签: c# asp.net-mvc razor


    【解决方案1】:

    我假设 Object 参数是 Model。因此,通过查看您上面的代码,我很确定以下内容会起作用:

    public String IncludeOnce(Func<Object, TemplateWriter> text) {
       string output = text(Model).ToString();
    
       //Do Stuff
    
       return output 
    }
    

    【讨论】:

    • 哇,不敢相信我想不通!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-08-02
    • 2015-02-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 2023-03-20
    • 2011-05-09
    相关资源
    最近更新 更多