简体   繁体   English

RouteValueDictionary到HtmlAttributes

[英]RouteValueDictionary to HtmlAttributes

I know I can add html attributes to my tag by doing something like: 我知道我可以通过以下操作将html属性添加到我的标签中:

var htmlAttributes = new RouteValueDictionary { { "data-foo", "bar" } };
var tag = new TagBuilder("div");
tag.MergeAttributes(htmlAttributes );
@tag

Output: 输出:

<div data-foo="bar"></div>

I wonder if I can add attributes in a similar way by using markup instead of a tag builder. 我想知道是否可以通过使用标记而不是标签构建器以类似的方式添加属性。 Maybe something like: 也许像这样:

var htmlAttributes = new RouteValueDictionary { { "data-foo", "bar" } };
<div @htmlAttributes.ToHtmlAttributes() ></div>

Expected output: 预期产量:

<div data-foo="bar"></div>

Clearly, I wouldn't be able to handle merge conflicts this way. 显然,我无法以这种方式处理合并冲突。 However, I think it's worth it because the second way is so much more readable. 但是,我认为这是值得的,因为第二种方法更具可读性。

You can write your own extension method: 您可以编写自己的扩展方法:

namespace SomeNamespace
{
    public static class RouteValueDictionaryExtensions
    {
        public static IHtmlString ToHtmlAttributes(this RouteValueDictionary dictionary)
        {
            var sb = new StringBuilder();
            foreach (var kvp in dictionary)
            {
                sb.Append(string.Format("{0}=\"{1}\" ", kvp.Key, kvp.Value));
            }
            return new HtmlString(sb.ToString());
        }
    }
}

which will be used exactly how you've described: 它将完全按照您的描述使用:

@using SomeNamespace    
@{
    var htmlAttributes = new RouteValueDictionary
        {
            {"data-foo", "bar"},
            {"data-bar", "foo"}
        };
}

<div @htmlAttributes.ToHtmlAttributes()> </div>

the result is: 结果是:

<div data-foo="bar" data-bar="foo" > </div>

Edit: 编辑:

If you want to use TagBuilder , you can alternatively write another extension which uses it internally: 如果要使用TagBuilder ,则可以编写另一个内部使用它的扩展:

public static IHtmlString Tag(this HtmlHelper helper, 
                              RouteValueDictionary dictionary, 
                              string tagName)
{
    var tag = new TagBuilder(tagName);
    tag.MergeAttributes(dictionary);
    return new HtmlString(tag.ToString());
}

and the usage shown below below gives the same output html as previously: 并且下面显示的用法提供了与以前相同的输出html:

@Html.Tag(htmlAttributes, "div")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM