0

我有一个像这样的扩展方法来创建一个按钮跨度:

public static HtmlString Ext1(this HtmlHelper helper, string css)
{
   var tag = new TagBuilder("span");

   tag.AddCssClass(css);
   ...
   return new HtmlString(tag.ToString());
}

我创建了另一个扩展来向 HtmlString 添加属性......就像这样:

public static HtmlString Ext2(this HtmlString helper, string attr)
{
   // need add attr to HtmlString and return
   return new HtmlString(newHtmlGenerated);
}

使用@Html.Ext1("class1").Ext2("1234")应该使用 css 和 attr 创建一个跨度...

我怎样才能做到这一点?

谢谢

4

1 回答 1

1

Like @levelnis said, you cannot create a TagBuilder from Html, you can only create it from a tag name. You have to use something that will parse the Html back into a concrete type that allows you to access the attibutes. XDocument will do this nicely. Try changing your Ext2 method to this:

public static HtmlString Ext2(this HtmlString helper, string attr)
{
    var doc = XDocument.Parse(helper.ToHtmlString());
    doc.Element(doc.Root.Name).SetAttributeValue("test", attr);
    return new HtmlString(doc.ToString());
}

XDocument is in the System.Xml.Linq namespace.

于 2013-08-22T18:35:04.087 回答