2013-05-07 85 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方法来添加您自己的属性。 干杯