2

我知道我可以通过执行以下操作将 html 属性添加到我的标签:

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

输出:

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

我想知道是否可以通过使用标记而不是标签生成器以类似的方式添加属性。也许是这样的:

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

预期输出:

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

显然,我无法以这种方式处理合并冲突。但是,我认为这是值得的,因为第二种方式更具可读性。

4

1 回答 1

4

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:

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.Tag(htmlAttributes, "div")
于 2013-09-04T16:08:17.070 回答