我想出了一个可链接的 HtmlAttribute 类和一些 Html 扩展方法来允许下面的 Razor 语法:
<ul>
@foreach (var mi in items) {
<li @Html.Css("selected", mi.Selected)>
<a href="@mi.Href" @Html.Attr("title", mi.Title)>@mi.Text</a>
</li>
}
</ul>
这是 HtmlAttribute 类:
public class HtmlAttribute : IHtmlString
{
private string _InternalValue = String.Empty;
private string _Seperator;
public string Name { get; set; }
public string Value { get; set; }
public bool Condition { get; set; }
public HtmlAttribute(string name)
: this(name, null)
{
}
public HtmlAttribute( string name, string seperator )
{
Name = name;
_Seperator = seperator ?? " ";
}
public HtmlAttribute Add(string value)
{
return Add(value, true);
}
public HtmlAttribute Add(string value, bool condition)
{
if (!String.IsNullOrWhiteSpace(value) && condition)
_InternalValue += value + _Seperator;
return this;
}
public string ToHtmlString()
{
if (!String.IsNullOrWhiteSpace(_InternalValue))
_InternalValue = String.Format("{0}=\"{1}\"", Name, _InternalValue.Substring(0, _InternalValue.Length - _Seperator.Length));
return _InternalValue;
}
}
额外信息:“分隔符”用于将属性的多个值链接在一起。这对于多个 css 类名(使用空格)或可能使用 String.Empty 来构建依赖于多个条件的值(通过使用 .Add() 方法)很有用
以下是 Html Extension 辅助方法:
public static class Extensions
{
public static HtmlAttribute Css(this HtmlHelper html, string value)
{
return Css(html, value, true);
}
public static HtmlAttribute Css(this HtmlHelper html, string value, bool condition)
{
return Css(html, null, value, condition);
}
public static HtmlAttribute Css(this HtmlHelper html, string seperator, string value, bool condition)
{
return new HtmlAttribute("class", seperator).Add(value, condition);
}
public static HtmlAttribute Attr(this HtmlHelper html, string name, string value)
{
return Attr(html, name, value, true);
}
public static HtmlAttribute Attr(this HtmlHelper html, string name, string value, bool condition)
{
return Attr(html, name, null, value, condition);
}
public static HtmlAttribute Attr(this HtmlHelper html, string name, string seperator, string value, bool condition)
{
return new HtmlAttribute(name, seperator).Add(value, condition);
}
}
让我知道它们是否有用。
谢谢,
李