He creado una clase de HtmlAttribute encadenable y algunos métodos de extensión Html para permitir el Razo sintaxis r a continuación:
<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>
Aquí está la clase 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;
}
}
Información adicional: El "separador" se utiliza para encadenar varios valores para un atributo. Esto puede ser útil para múltiples nombres de clase css (use un espacio) o tal vez use String.Empty para construir un valor que dependa de múltiples condiciones (usando el método .Add())
Y aquí están los métodos de ayuda de la extensión Html :
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);
}
}
Avísame si son útiles.
Gracias,
Lee
La última versión de la maquinilla de afeitar ahora tiene soporte para esto. Ver la respuesta a continuación. – JarrettV