2013-05-07 46 views
5

我想爲dropdownlist創建一個自定義htmlhelper(擴展方法),以接受selectlistitem的Option標籤中的自定義屬性。MVC中SelectListItem的自定義屬性

我在我的模型類中有一個屬性,我想將其作爲屬性包含在選擇列表的選項標記中。

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

我所遇到相當具體到我想要的各種例子,但非。

回答

4

試試這個:

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

是的,你可以自己創建它。 創建一個擴展方法,該方法將接受包含其所有必需屬性的Object列表。使用TagBuilder創建標籤並使用它的MergeAttribute方法來添加您自己的屬性。 乾杯