That's what I'm doing:
I have this class:
public class HtmlValues : Dictionary<string,object> { public HtmlValues Class(string ClassName) { if (this.ContainsKey("class")) { ClassName = String.Format("{0} {1}", this["class"], ClassName); this.Remove("class"); } return this.WithValue("class", ClassName); } public HtmlValues Name(string Name) { return this.WithValue("name", Name); } public HtmlValues Style(string Style) { return this.WithValue("style", Style); } public HtmlValues MaxLength(int Length) { return this.WithValue("maxlength", Length.ToString()); } public HtmlValues RTL() { return this.WithValue("dir", "rtl"); } public HtmlValues With(string Attribute, string Value) { return this.WithValue(Attribute, Value); } public static HtmlValues WithClass(string CssClass) { return new HtmlValues().Class(CssClass); } public HtmlValues Data(string key, string value) { return this.WithValue("data-" + key, value); } }
Using this extension method:
public static class Extensions { public static T WithValue<T>(this T dict, string key, object value) where T : IDictionary<string, object> { dict.Add(key, value); return dict; } }
Then my Razor looks like this:
@Html.TextBoxFor(model => model.SomeProperty, HtmlValues.WithClass("SomeClass"))
This may seem redundant, but in practice it is pretty good, as it allows the chain to add attributes / values ββto the element in a pleasant, understandable for the reader style.
@Html.TextBoxFor(model => model.SomeProperty, HtmlValues.WithClass("SomeClass") .Class("someotherClass") .Data("Some-Jquery-Data-Thing") .With("Nonstandard-Attribute","Its-Value"))
source share