I am creating a custom helper method for a Drop Down List with the following signature:
public static MvcHtmlString MyCustomDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
Within the method, I can do the following to get the selected value:
var Value = ((SelectList)selectList).SelectedValue);
In my helper method, I need to find out what the selected text is as well, and not just the value. How will I get that?
If you already have selected value you can just iterate through the
IEnumerabletrying to find the selectedSelectListItem:From my opinion, casting to
SelectListis not the best option to find selected value, this casting could throwInvalidCastExceptionwhen real type ofselectListvariable is other thanSelectList.In most cases your model contains a value that should be selected in the drop down list. You can get this value using
ModelMetadataclasses as follows: