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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With