2009-08-22 23 views
23

En asp.net mvc siempre veo los helpers incorporados en html que siempre tienen el objeto htmlAttirbutes.Cómo obtener valores fuera del objeto HtmlAttributes

Entonces suelo hacer algo nuevo {@id = "test", @ class = "myClass"}.

¿Cómo se extrae un parámetro como este en mis propios helpers html?

Me gusta Estoy utilizando "HtmlTextWriterTag" es su manera de que pueda pasar todo este objeto al escritor y lo descubrió o qué?

¿Cómo funciona esto con los grandes ayudantes html?

Me gusta Estoy haciendo un ayudante de html y usa todas estas etiquetas.

Table 
thead 
tfooter 
tbody 
tr 
td 
a 
img 

¿Eso significa que tengo que hacer un atributo html para cada una de estas etiquetas?

Respuesta

36

por lo general hago algo como esto:

public static string Label(this HtmlHelper htmlHelper, string forName, string labelText, object htmlAttributes) 
    { 
     return Label(htmlHelper, forName, labelText, new RouteValueDictionary(htmlAttributes)); 
    } 

    public static string Label(this HtmlHelper htmlHelper, string forName, string labelText, 
           IDictionary<string, object> htmlAttributes) 
    { 
     // Get the id 
     if (htmlAttributes.ContainsKey("Id")) 
     { 
      string id = htmlAttributes["Id"] as string; 
     } 

     TagBuilder tagBuilder = new TagBuilder("label"); 
     tagBuilder.MergeAttributes(htmlAttributes); 
     tagBuilder.MergeAttribute("for", forName, true); 
     tagBuilder.SetInnerText(labelText); 
     return tagBuilder.ToString(); 
    } 

te sugieren para descargar la fuente de ASP.NET MVC del CodePlex y echar un vistazo a la incorporada en ayudantes HTML.

+0

resulta que su ejemplo es más informativo que la fuente. No pude entender cómo funcionaba la fuente, ya que se esperaba un IDictionary (como su etiqueta) pero estaba tratando de pasarle el objeto anónimo. Una vez que te vi convertirlo en un RouteValueDictionary tiene más sentido. –

+2

Esto no parece funcionar con atributos como data_bind – SimonGates

3

puede transformar las htmlAttirbutes objeto a una representación de cadena de atributo/valor de la siguiente manera:

var htmlAttributes = new { id="myid", @class="myclass" }; 

string string_htmlAttributes = ""; 
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes)) 
{ 
    string_htmlAttributes += string.Format("{0}=\"{1}\" ", property.Name.Replace('_', '-'), property.GetValue(htmlAttributes)); 
} 

PropertyDescriptor pertenecen a la clase System.ComponentModel

1

que utilizar una combinación de ambos métodos (Chtiwi Malek y rrejc) propuesto anteriormente y funciona de maravilla.

Con este método, convertirá data_id en data-id. También sobrescribirá los valores de atributo predeterminados que haya establecido anteriormente.

using System.ComponentModel; 
... 


public static MvcHtmlString RequiredLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes) 
{ 
    var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); 

    string htmlFieldName = ExpressionHelper.GetExpressionText(expression); 
    string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last(); 

    if (String.IsNullOrEmpty(labelText)) 
     return MvcHtmlString.Empty; 

    var label = new TagBuilder("label"); 
    label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); 

    foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes)) 
    { 
     // By adding the 'true' as the third parameter, you can overwrite whatever default attribute you have set earlier. 
     label.MergeAttribute(prop.Name.Replace('_', '-'), prop.GetValue(htmlAttributes).ToString(), true); 
    } 
    label.InnerHtml = labelText; 
    return MvcHtmlString.Create(label.ToString()); 
} 

Tenga en cuenta el comentario sobre la sobrescritura de un atributo que tiene un valor predeterminado en el código en el foreach.

Cuestiones relacionadas