创建一个返回Razor @标签的辅助函数?

努力寻找我的问题的答案,因为我不确定剃刀标签的’类型’是什么。

基本上我想创建一个帮助器,沿着这些方向做一些事情:

public static xxxxxxx ScriptTag(this HtmlHelper htmlHelper, string url) { return @; } 

我想要这个的原因是我正在实现这篇文章中概述的扩展方法。

基本上而不是必须做:

 @Html.Resource(@, "js")` 

我希望能够做到:

 @Html.Resource(Html.ScriptTag("Scripts/jquery-1.4.4.min.js"), "js"); 

我是在这里超越星星还是可能的?

克里斯

我没有在ScriptTag助手( js )中看到第二个参数的用法。 帮助程序称为ScriptTag,因此很明显它将呈现脚本。 另外,为什么你需要那些2个嵌套的助手,当你可以直接拥有:

 @Html.Resource("Scripts/jquery-1.4.4.min.js", "js") 

但无论如何,如果你需要这样的语法,你可以使用Razor Templated Delegates :

 public static class HtmlExtensions { public static HelperResult ScriptTag(this HtmlHelper htmlHelper, string url, string type) { var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); var script = new TagBuilder("script"); script.Attributes["type"] = "text/javascript"; script.Attributes["src"] = urlHelper.Content("~/" + url); return new HelperResult(writer => { writer.Write(script.ToString(TagRenderMode.Normal)); }); } public static IHtmlString Resource(this HtmlHelper htmlHelper, HelperResult renderer) { return renderer; } } 

正如我们所看到的,在这种情况下, Resource扩展方法并没有带来太多价值。

您可以通过为HtmlHelper类型创建扩展方法来解决此问题。

例如:

 public static MvcHtmlString ScriptTag(this HtmlHelper htmlHelper, string contentPath, string scriptType) { var httpContext = htmlHelper.ViewContext.HttpContext; var scriptTag = String.Format("", UrlHelper.GenerateContentUrl(contentPath, httpContext), scriptType); return new MvcHtmlString(scriptTag); } 

然后,您可以使用自定义Html帮助程序方法,如下所示:

 @Html.ScriptTag("Scripts/jquery1.6.1.min.js", "javascript/text"); 

当函数的结果是纯HTML时,我喜欢使用Razor Helpers 。

在视图文件中,创建一个类似的语句:

 @helper ScriptTag(string url) {  } 

然后用法就像

 @ScriptTag("myScript.js") 

Razor Helpers返回HTML中的HTML