创建一个返回剃刀@标签的辅助功能? [英] Create a helper function that returns Razor @ tags?

查看:104
本文介绍了创建一个返回剃刀@标签的辅助功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

苦苦寻找的答案,我的问题,因为我不完全相信剃刀标签是什么类型。

Struggling to find an answer to my question, as I'm not exactly sure what 'type' a razor tag is.

基本上我想创建一个帮手,做这些方针的东西:

Essentially I want to create a helper that does something along these lines:

public static xxxxxxx ScriptTag(this HtmlHelper htmlHelper, string url)
{
      return @<script type="text/javascript" src="@Url.Content("~/" + url)" />;
}

我想这个的原因是,我实现了在<一个概括的扩展方法href=\"http://stackoverflow.com/questions/5433531/using-sections-in-editor-display-templates/5433722#5433722\">this帖子。

基本上而不是必须做的:

Basically rather than have to do:

@Html.Resource(@<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>, "js")`

我希望能够做到:

I want to be able to do:

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

我是不是达到了超越这里的明星或者是这可能吗?

Am I reaching beyond the stars here or is this possible?

克里斯

推荐答案

我不太看到你的 ScriptTag 助手的第二个参数的用法( JS )。助手被称为ScriptTag所以它是pretty明显,它将呈现一个脚本。另外你为什么需要这些嵌套2像助手,当你可以直接有:

I don't quite see the usage of the second parameter in your ScriptTag helper (js). The helper is called ScriptTag so it is pretty obvious that it will render a script. Also why do you need those 2 nested helpers like that when you can directly have:

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

但无论如何,如果你需要这样的语法,你可以使用剃刀模板化代表的:

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;
    }
}

我们可以看到在这种情况下,资源扩展方法,并没有带来太大的价值。

As we can see the Resource extension method in this case doesn't bring much value.

这篇关于创建一个返回剃刀@标签的辅助功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆