微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc-3 – ASP.NET MVC3中的“返回类型”

我试图弄清楚如何(或者是否可能)编写可以通过以下方式调用HTML帮助器方法

@Html.MyHelper("some string parameter",@<text>
    <table>
      <tr>
        <td>some html content in a "template" @Model.someProperty</td>
      </tr>
    </table>
</text>)

这个想法是允许用户创建自己的模板以传递给帮助者.随着一些讨论,我想出了这个代码

public static MvcHtmlString jQueryTmpl(this HtmlHelper htmlHelper,string templateId,Func<object,HelperResult> template) {
    return MvcHtmlString.Create("<script id='" + templateId + "' type='x-jquery-tmpl'>" + template.Invoke(null) + "</script>");
}

这有效,但我不明白为什么或者它是否有意义.有人可以解释一下< text>实际上是在后台,我怎么能在上面描述的上下文中使用它?

谢谢

解决方法

特殊的< text>标签的存在是为了允许您在Razor解析器通常选择代码模式的情况下强制从代码转换标记.例如,if语句的主体认为代码模式:

@if(condition) {
    // still in code mode
}

剃刀解析器具有在检测到标记自动切换到标记模式的逻辑:

@if(condition) {
    <div>Hello @Model.Name</div>
}

但是,您可能希望切换到标记模式而不实际发出一些标记(因为上面的情况会发出< div>标记).您可以使用< text>阻止或@:语法:

@if(condition) {
    // Code mode
    <text>Hello @Model.Name <!-- Markup mode --></text>
    // Code mode again
}

@if(condition) {
    // Code mode
    @:Hello @Model.Name<!-- Will stay in markup mode till end of line -->
    // Code mode again
}

回到你的问题:在这种情况下你不需要< text>标记,因为您的模板已经有标记将触发Razor中的正确行为.你可以写:

@Html.MyHelper("some string parameter",@<table>
    <tr>
      <td>some html content in a "template" @Model.someProperty</td>
    </tr>
</table>)

这样做的原因是因为代码上下文中的Razor解析器识别@< tag>< / tag>模式并将其转换为Func< object,HelperResult>.

在您的示例中,生成代码看起来大致如下:

Write(Html.MyHelper("some string parameter",item => new System.Web.WebPages.HelperResult(__razor_template_writer => {
    WriteLiteralTo(@__razor_template_writer,"<table>\r\n      <tr>\r\n        <td>some html content in a \"template\" ");
    Writeto(@__razor_template_writer,Model.someProperty);
    WriteLiteralTo(@__razor_template_writer,"</td>\r\n      </tr>\r\n    </table>");
})));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐