Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Attributes for SelectlistItem in MVC

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.

like image 473
lacoder Avatar asked Oct 04 '22 04:10

lacoder


1 Answers

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());
}
like image 105
von v. Avatar answered Oct 06 '22 17:10

von v.