Code below doesn\'t seems clean. Any suggestion to improve the code?
class=\
I use a small helper method that will conditionally add an attribute if the value is non-empty, and, if defined, when a Boolean function expression evaluates to true
:
public static MvcHtmlString Attr(this HtmlHelper helper, string name, string value, Func condition = null)
{
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
{
return MvcHtmlString.Empty;
}
var render = condition != null ? condition() : true;
return render ?
new MvcHtmlString(string.Format("{0}=\"{1}\"", name, HttpUtility.HtmlAttributeEncode(value))) :
MvcHtmlString.Empty;
}
Once defined, I can use this method in my Razor views:
- example.isNew))>
...
The above code will render
if example.isNew == true
, if not will omit the entire class
attribute.