Custom Attributes for SelectlistItem in MVC

人盡茶涼 提交于 2019-12-04 07:59:42

Try this:

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

Yeah you can create it by your own. Create one Extension method which will accept a list of Object which contains all required properties of it. Use TagBuilder to create Tags and use MergeAttribute method of it to add your own attribute to it. Cheers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!