I’m trying to figure out how (or if it’s possible) to write an HTML helper method that could be invoked in the following manner:
@Html.MyHelper("some string parameter", @<text>
<table>
<tr>
<td>some html content in a "template" @Model.SomeProperty</td>
</tr>
</table>
</text>)
The idea is to allow a user to create their own template to be passed to the helper. With some poking around I came up with this code:
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>");
}
and this works, but I don’t understand why or if it even makes sense. Could someone explain what <text> actually is in the background and how could I use it in the context I described above?
Thanks
The special
<text>tag exists to allow you to force a transition from code to markup in cases where the Razor parser would normally choose code mode. For example the body of anifstatement defaults to code mode:The razor parser has logic to automatically switch to markup mode if it detects a tag:
However you might want to switch to markup mode without actually emitting some tag (as the above case would emit the
<div>tags). You can either use a<text>block or the@:syntax:So back to your question: in this case you don’t need the
<text>tag because your template already has tags that will trigger the correct behavior in Razor. You could just write:The reason this works is because the Razor parser inside of a code context recognizes the
@<tag></tag>pattern and converts it into aFunc<object, HelperResult>.In your example the generated code would look roughly like this: