自定义属性在MVC SelectlistItem [英] Custom Attributes for SelectlistItem in MVC

查看:312
本文介绍了自定义属性在MVC SelectlistItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个自定义的HtmlHelper(扩展方法)的DropDownList接受的selectlistitem的选项标记的自定义属性。

I would like to create a custom htmlhelper(Extension Method) for dropdownlist to accept custom attributes in the Option tag of the selectlistitem.

我有一个属性在我的模型类,我想包括在选择列表的选项标记的属性。

I have a property in my model class, that I would like to include as an attribute in the option tag of the selectlist.

<期权价值=modelproperty =>< /选项>

我所遇到的各种例子,但非相当具体到我想要的东西。

I have come across various examples but non quite specific to what I would want.

推荐答案

试试这个:

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

这篇关于自定义属性在MVC SelectlistItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆