How can I treat a Nullable just like I do with Enum within the String.cshtml file?
Background: I have successfully implemented a custom Editor Template for my enums (implementing the String.cshtml within the Views/Shared/EditorTemplates/String.cshtml.
I understood that it works as a fallback type for Enums, so whenever you have
Html.EditorFor(m => m.PropertyOfTypeEnum)
It creates my correcly a dropdown in which I can select the options.
Problem: the issue arises when my PropertyOfTypeEnum is a Nullable<>. I don't understand exactly why, it does not fall back into the String.cshtml and therefore I can't treat it to render my dropdown list.
Further Info: I have double checked to see and it's actually NOT hitting my breakpoint at my String.cshtml.
Does anyone have any idea of how to treat it?
I am guessing that it is not working because calling ToString()
on a null object would fail, therefore it is not able to infer to use String.cshtml by looking at the data type (which is null Enum and not null string).
You can help your editor template along by specifying that it should be used:
Add [UIHint("String")]
in your view model for the required enum property.
Alternative solution:
I had to solve the same problem but used a different technique. I added an additional extension method for DropDownFor
that understand enums. For example:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
where TProperty : struct
{
IEnumerable<SelectListItem> selectList = DropDownHelper.ToSelectListItems<TProperty>();
return htmlHelper.DropDownListFor(expression, selectList);
}