【问题标题】:Custom Attributes for SelectlistItem in MVCMVC 中 SelectlistItem 的自定义属性
【发布时间】:2013-05-07 10:13:28
【问题描述】:

我想为下拉列表创建一个自定义 htmlhelper(扩展方法),以接受 selectlistitem 的 Option 标记中的自定义属性。

我的模型类中有一个属性,我想将其作为属性包含在选择列表的选项标签中。

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

我遇到了各种各样的例子,但并不是我想要的。

【问题讨论】:

    标签: asp.net-mvc html-helper


    【解决方案1】:

    试试这个:

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

    【讨论】:

      【解决方案2】:

      是的,您可以自己创建它。 创建一个扩展方法,该方法将接受一个包含所有必需属性的 Object 列表。使用 TagBuilder 创建标签并使用它的 MergeAttribute 方法将您自己的属性添加到它。 干杯

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多