Mar*_*arz 4 html-helper razor asp.net-mvc-3
我试图弄清楚如何(或者是否可能)编写可以通过以下方式调用的HTML帮助器方法:
@Html.MyHelper("some string parameter", @<text>
<table>
<tr>
<td>some html content in a "template" @Model.SomeProperty</td>
</tr>
</table>
</text>)
Run Code Online (Sandbox Code Playgroud)
这个想法是允许用户创建自己的模板以传递给帮助者.随着一些讨论,我想出了这个代码:
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>");
}
Run Code Online (Sandbox Code Playgroud)
这有效,但我不明白为什么或者它是否有意义.有人可以解释<text>实际背景是什么,我怎么能在上面描述的上下文中使用它?
谢谢
<text>存在特殊标记,允许您在Razor解析器通常选择代码模式的情况下强制从代码到标记的转换.例如,if语句的主体默认为代码模式:
@if(condition) {
// still in code mode
}
Run Code Online (Sandbox Code Playgroud)
剃刀解析器具有在检测到标记时自动切换到标记模式的逻辑:
@if(condition) {
<div>Hello @Model.Name</div>
}
Run Code Online (Sandbox Code Playgroud)
但是,您可能希望切换到标记模式而不实际发出一些标记(因为上面的情况会发出<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
}
Run Code Online (Sandbox Code Playgroud)
回到你的问题:在这种情况下你不需要<text>标签,因为你的模板已经有标签会触发Razor中的正确行为.你可以写:
@Html.MyHelper("some string parameter", @<table>
<tr>
<td>some html content in a "template" @Model.SomeProperty</td>
</tr>
</table>)
Run Code Online (Sandbox Code Playgroud)
这是有效的原因是因为代码上下文中的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>");
})));
Run Code Online (Sandbox Code Playgroud)