这就是我所做的:
我有这堂课:
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"))