这是我的做法:
我有这个类:
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;
}
}
那么我的 Razor 看起来像这样:
@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"))
new
中添加类似这样的内容:@Url.Action("Index", "Home", new { page, className="foo" }) - MilkyWayJoenew { @class= '...' }
,对吧? - asawyer