Actually, for this you can write an Extension class for HtmlHelper, but you need to implement many overrides, so the fastest solution I found was to write a dictionary extension.
To do this, you can use the class below:
public static class DictionaryExtensions { public static Dictionary<string, object> WithAttrIf(this Dictionary<string,object> dictionary,bool condition, string attrname, object value) { if (condition) dictionary[attrname] = value; return dictionary; } public static Dictionary<string, object> WithAttr(this Dictionary<string, object> dictionary, string attrname, object value) { dictionary[attrname] = value; return dictionary; } }
To use it, import the class into your view, and your view code looks like this:
@Html.TextBoxFor(m => m.FirstName, new Dictionary<string, object>().WithAttr("class","input-large").WithAttrIf(!string.IsNullOrWhiteSpace(Model.FirstName),"readonly","yes"))
You can add as many attributes as you want, since the extension method adds the value to the dictionary and returns the dictionary itself
Cagatay Kalan May 05 '13 at 22:22 2013-05-05 22:22
source share