加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC中SelectlistItem的自定义属性

发布时间:2020-12-16 03:28:41 所属栏目:asp.Net 来源:网络整理
导读:我想为dropdownlist创建一个自定义htmlhelper(扩展方法),以接受selectlistitem的Option标记中的自定义属性. 我的模型类中有一个属性,我想在选择列表的选项标签中包含一个属性. 即 option value =“”modelproperty =“” / option 我遇到了各种各样的例子,但
我想为dropdownlist创建一个自定义htmlhelper(扩展方法),以接受selectlistitem的Option标记中的自定义属性.

我的模型类中有一个属性,我想在选择列表的选项标签中包含一个属性.

即< option value =“”modelproperty =“”>< / option>

我遇到了各种各样的例子,但对我想要的东西并不十分具体.

解决方法

试试这个:

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());
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读