2013-05-07 16 views
5

Vorrei creare un htmlhelper personalizzato (metodo di estensione) per dropdownlist per accettare attributi personalizzati nel tag Option del selectlistitem.Attributi personalizzati per SelectlistItem in MVC

Ho una proprietà nella mia classe modello, che vorrei includere come attributo nel tag opzione della selectlist.

cioè <option value ="" modelproperty =""></option>

mi sono imbattuto in diversi esempi, ma non abbastanza specifici per quello che vorrei.

risposta

4

Prova questo:

public static MvcHtmlString CustomDropdown<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expression, 
    IEnumerable<SelectListItem> listOfValues, 
    string classPropName) 
{ 
    var model = htmlHelper.ViewData.Model; 
    var metaData = ModelMetadata 
     .FromLambdaExpression(expression, htmlHelper.ViewData);    
    var tb = new TagBuilder("select"); 

    if (listOfValues != null) 
    { 
     tb.MergeAttribute("id", metaData.PropertyName);     

     var prop = model 
      .GetType() 
      .GetProperties() 
      .FirstOrDefault(x => x.Name == classPropName); 

     foreach (var item in listOfValues) 
     { 
      var option = new TagBuilder("option"); 
      option.MergeAttribute("value", item.Value); 
      option.InnerHtml = item.Text; 
      if (prop != null) 
      { 
       // if the prop's value cannot be converted to string 
       // then this will throw a run-time exception 
       // so you better handle this, put inside a try-catch 
       option.MergeAttribute(classPropName, 
        (string)prop.GetValue(model));  
      } 
      tb.InnerHtml += option.ToString(); 
     } 
    } 

    return MvcHtmlString.Create(tb.ToString()); 
} 
0

Sì, puoi crearlo da solo. Creare un metodo di estensione che accetterà un elenco di oggetti che contiene tutte le proprietà richieste di esso. Utilizzare TagBuilder per creare tag e utilizzare il metodo MergeAttribute per aggiungere il proprio attributo ad esso. Acclamazioni

Problemi correlati