在HtmlHelper扩展方法中使用Anonymous对象

时间:2014-04-23 15:21:35

标签: c# .net asp.net-mvc html-helper anonymous-class

我想扩展HtmlHelper,以便使用自定义属性呈现脚本标记(例如'async')

我想像这样使用它

@Html.RenderBundleScript("/mybundleName", new { async = ""})

这是我的代码,但不起作用(特别是attributes.ToString()提供: System.Web.Routing.RouteValueDictionary 而不是 async 或< EM> async='' 的):

public static IHtmlString RenderBundleScript(this HtmlHelper htmlHelper, 
                               string bundlePath, object htmlAttributes)
{
    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    string attributesValue = (attributes == null) ? 
                             string.Empty : attributes.ToString();
    if (string.IsNullOrEmpty(attributesValue))
    {
        return Scripts.Render(bundlePath);
    }
    else
    {
        //var tag = new TagBuilder("script");
        // tag.MergeAttribute() ???
        return Scripts.RenderFormat("<script src='{0}' " + 
                       attributesValue + 
                       " type='text/javascript'></script>", bundlePath);
    }
}

1 个答案:

答案 0 :(得分:3)

scripts类有一个方法Scripts.RenderFormat,它接受​​一个格式字符串,用于呈现包中的每个脚本。

这对您的扩展方法来说非常方便。您可以使用html属性为脚本标记创建格式字符串。此格式字符串如下所示:

 <script async="" fooAttrib="1" src="{0}" type="text/javascript"></script>

因此,您可以通过以下方式更新扩展方法:

public static IHtmlString RenderBundleScript(this HtmlHelper htmlHelper,
                        string bundlePath, object htmlAttributes)
{
    if (htmlAttributes == null)
    {
        return Scripts.Render(bundlePath);
    }
    else
    {            
        //Create format string for the script tags, including additional html attributes    
        TagBuilder tag = new TagBuilder("script");
        tag.Attributes.Add("src", "{0}");
        tag.Attributes.Add("type", "text/javascript");
        var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        foreach (var key in attributes.Keys)
        {
            tag.Attributes.Add(key, attributes[key].ToString());
        }                
        var tagFormat = tag.ToString(TagRenderMode.Normal);

        //render the scripts in the bundle using the custom format
        return Scripts.RenderFormat(tagFormat, bundlePath);
    }
}

如果您按以下方式调用它:

@Html.RenderBundleScript("~/bundles/jqueryval", new {async = "", dummy="1"})

它将呈现此输出:

<script async="" dummy="1" src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script async="" dummy="1" src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>

希望它有所帮助!