Issue with TagBuilder.MergeAttribute for parameter null
Posted
by
The Yur
on Stack Overflow
See other posts from Stack Overflow
or by The Yur
Published on 2014-06-04T15:22:04Z
Indexed on
2014/06/04
15:24 UTC
Read the original article
Hit count: 182
I would like to use Razor's feature not to produce attribute output inside a tag in case when attribute's value is null. So when Razor meets <div class="@var"> where @var is null, the output will be mere <div>. I've created some Html extension method to write text inside tag. The method takes header text, level (h1..h6), and html attributes as simple object. The code is:
public static MvcHtmlString WriteHeader(this HtmlHelper html, string s, int? hLevel = 1, object htmlAttributes = null)
{
if ((hLevel == null) ||
(hLevel < 1 || hLevel > 4) ||
(s.IsNullOrWhiteSpace()))
return new MvcHtmlString("");
string cssClass = null, cssId = null, cssStyle = null;
if (htmlAttributes != null)
{
var T = htmlAttributes.GetType();
var propInfo = T.GetProperty("class");
var o = propInfo.GetValue(htmlAttributes);
cssClass = o.ToString().IsNullOrWhiteSpace() ? null : o.ToString();
propInfo = T.GetProperty("id");
o = propInfo.GetValue(htmlAttributes);
cssId = o.ToString().IsNullOrWhiteSpace() ? null : o.ToString();
propInfo = T.GetProperty("style");
o = propInfo.GetValue(htmlAttributes);
cssStyle = o.ToString().IsNullOrWhiteSpace() ? null : o.ToString();
}
var hTag = new TagBuilder("h" + hLevel);
hTag.MergeAttribute("id", cssId);
hTag.MergeAttribute("class", cssClass);
hTag.MergeAttribute("style", cssStyle);
hTag.InnerHtml = s;
return new MvcHtmlString(hTag.ToString());
}
I found that in spite of null values for "class" and "style" attributes TagBuilder still puts them as empty strings, like <h1 class="" style=""> But for id attribute it surprisingly works, so when id's value is null, there is no id attribute in tag.
My question - is such behavior something that should actually happen? How can I achieve absent attributes with null values using TagBuilder?
I tried this in VS2013, MVC 5.
© Stack Overflow or respective owner