Code below doesn\'t seems clean. Any suggestion to improve the code?
class=\
Based on defrosts answer here an adaptation, taking an object instead of a string:
public static MvcHtmlString ConditionalAttr(this HtmlHelper helper, string attributeName, object value, Func condition)
{
if (string.IsNullOrEmpty(attributeName) || value == null)
{
return MvcHtmlString.Empty;
}
var render = condition != null ? condition() : true;
return render ?
new MvcHtmlString($"{attributeName}=\"{HttpUtility.HtmlAttributeEncode(value.ToString())}\"") :
MvcHtmlString.Empty;
}
This way you don't have to turn your other datatypes in strings before passing them, saving a fiew .ToString().
There is a difference tho: passing an empty string will still render.
As example:
@Html.ConditionalAttr("data-foo", "", () => Model.IsFooNeeded)
// Ouput:
data-foo=""