1

I've searched about a bit and can't find an answer specifically to my question.

I have an Enum:

public enum CodeType
{
    NotSpecified,
    Absent,
    NoAbsence,
    Other,
    Missing
}

The above Enum is stored in a struct. I am trying to edit the stored Enum in a view using a DropDownList, which works great, except my only issue is I am trying to set the default value of that DropDownList to the model's stored Enum. See below:

@Html.DropDownList("c", EnumHelper.GetSelectList(typeof(CodeType)),Enum.GetValues(typeof(CodeType)))

As the second argument, I have tried using:

@Html.DropDownList("c", EnumHelper.GetSelectList(typeof(CodeType)),Enum.GetValues(typeof(Model.CodeType.ToString())))

However, that does display the stored Enum value as a string in the DropDownList, but if the user hits the submit button, I get an error for a null variable unless the user explicitly clicks on the DropDownList and selects an item.

Any ideas how I can properly use Model.CodeType as the default value in the DropDownList?

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Izacch
  • 383
  • 3
  • 10
  • FYI you dont have to provide your tags in title or in question thats what tags are for we all know you are using C# and MVC4 since you tagged your question with that - dont need to mention it twice. – Rand Random Apr 30 '18 at 14:57
  • Ah sorry, I realised they were in the tags, but wanted to make sure people knew what I was using :) – Izacch Apr 30 '18 at 15:00
  • If your property is `CodeType`, then you need to bind to that property - `@Html.DropDownListFor(m => m.CodeType, EnumHelper.GetSelectList(....` –  Apr 30 '18 at 23:06

1 Answers1

1

Try setting Model.CodeType to your desired enum from inside your controller's GET method before passing the model into the view.

Immorality
  • 2,164
  • 2
  • 12
  • 24
  • Model.CodeType is set to one of the enumerables in the Enum CodeType, if that makes sense. I wish for the value already stored in Model.CodeType to be the default value in the DropDownList – Izacch Apr 30 '18 at 14:57