I have a view model that contains enum with nullable type like this one :
public StudyLevel? studyLevel { get; set; }
I have made custom html helper to display a dropdownlist for rendering the enum into the view, the nullable case is displayed using
<option value="null">No value</option>
the problem is that when i submit the form modelstate give me the error :
studylevel cannot be "null" .
Could you suggest me any way to help me handle the nullable type in the view ?
I might be wrong but I am pretty sure there are some limitations around nullable enums and the MVC default model binder. I would recommend having a state which represents " no value " instead eg
StudyLevel.None
That way you don't need to deal with checking for null
etc.
What if you change your html helper to display the null value like this?
<option>No value</option>
Or like this?
<option value="">No value</option>
Edit: A better option (IMO) is to create a collection of SelectListItem
and then use a built-in HTML helper. Please take a look into this article I created some months ago, it may help you. You can use it like this:
@Html.EnumDropDownList<StudyLevel?>("studyLevel", "No value")
More info here:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.