What do you think of my simple solution? It works easily with both possible types of HtmlAttributes :
Dictionary<string, object>Anonymous Object :
First add the following simple extension class to your project:
public static class HtmlAttributesExtensions { public static IDictionary<string, object> AddHtmlAttrItem(this object obj, string name, object value, bool condition) { var items= !condition ? new RouteValueDictionary(obj) : new RouteValueDictionary(obj) {{name, value}}; return UnderlineToDashInDictionaryKeys(items); } public static IDictionary<string, object> AddHtmlAttrItem(this IDictionary<string, object> dictSource, string name, object value, bool condition) { if (!condition) return dictSource; dictSource.Add(name, value); return UnderlineToDashInDictionaryKeys(dictSource); } private static IDictionary<string, object> UnderlineToDashInDictionaryKeys(IDictionary<string,object> items) { var newItems = new RouteValueDictionary(); foreach (var item in items) { newItems.Add(item.Key.Replace("_", "-"), item.Value); } return newItems; } }
Now in view mode:
Example1 ( HtmlAttributes enter Anonymous Object )
@{ var hasDisabled=true; } @Html.CheckBox("CheckBox1" , true , new { @class = "Class1"} .AddHtmlAttrItem("disabled", "disabled", hasDisabled)) .
Example 2 ( HtmlAttributes type as Dictionary<string, object> )
@Html.CheckBox("CheckBox1" , true , new Dictionary<string, object> { { "class", "Class1" } .AddHtmlAttrItem("disabled", "disabled", hasDisabled)) .
Now just change the value of makeItReadOnly to true to false !
Example 3 (Several conditional properties)
@{ var hasDisabled=true; var hasMax=false ; var hasMin=true ; } @Html.CheckBox("CheckBox1" , true , new { @class = "Class1"} .AddHtmlAttrItem("disabled", "disabled", hasDisabled) .AddHtmlAttrItem("data-max", "100", hasMax) .AddHtmlAttrItem("data-min", "50", hasMin)) .