これが私がすることです:
私はこのクラスを持っています:
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);
}
}
この拡張メソッドを使用すると、次のようになります。
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;
}
}
次に、私のかみそりは次のようになります。
@Html.TextBoxFor(model => model.SomeProperty, HtmlValues.WithClass("SomeClass"))
これはやり過ぎのように思えるかもしれませんが、読者のファッションに意味のある流暢な方法で要素に属性/値を連鎖的に追加できるため、実際にはかなり便利です。
@Html.TextBoxFor(model => model.SomeProperty,
HtmlValues.WithClass("SomeClass")
.Class("someotherClass")
.Data("Some-Jquery-Data-Thing")
.With("Nonstandard-Attribute","Its-Value"))