Custom Attributes for SelectlistItem in MVC

一笑奈何 提交于 2019-12-21 17:20:07

问题


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.

i.e <option value ="" modelproperty =""></option>

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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/16416498/custom-attributes-for-selectlistitem-in-mvc

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