2

On my MVC form, I need to bind a drop down box to an enumeration on my ViewModel. The best way I found to do that is described here.

It appeared to work at first, but now that I've added validation to my form, I've discovered it does not bind back to the ViewModel.

Here's my razor code:

<div class="editor-field">
    @Html.DropDownListFor(model => model.response, 
                          new SelectList(Enum.GetValues(typeof(Vouchers.Models.ResponseType))),
                          "Please Select")
</div>

And here's my view model definition for the field:

[DisplayName("Response")]
[Range(1, int.MaxValue, ErrorMessage = "You must select a response before submitting this form.")]
public ResponseType response { get; set; }

The problem is that I cannot submit the form; even after selecting a response from my drop down, the Validation error message for the Range attribute is displayed and the client side validation prevents the form from submitting.

I believe this is because the SelectList for the drop down contains only the string names of the enum, not the underlying integer value.

How can I solve this problem?

Community
  • 1
  • 1
Slider345
  • 4,558
  • 7
  • 39
  • 47
  • Why do you need a `Range` attribute when you know the range you are binding too and already have `Required` ? – asawyer Oct 05 '12 at 18:00
  • The Required attribute doesn't seem to be work on its own--the response field defaults to the value 0. Actually I could just take Required out, it seems to have no effect – Slider345 Oct 05 '12 at 18:21

1 Answers1

5

Create Dictionary where Key will be integer representation of the enum and string- the name of enum.

@Html.DropDownListFor(model => model.response, 
                      new SelectList(Enum.GetValues(typeof(Vouchers.Models.ResponseType)).OfType<Vouchers.Models.VoucherResponseType>().ToDictionary(x => Convert.ToInt32(x), y => y.ToString()), "Key", "Value"), "Please Select")

Sorry for possible errors, I have not tried it.

Slider345
  • 4,558
  • 7
  • 39
  • 47
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • Thanks this worked! Although it turned out a cast was needed in order to go from the System.Array returned by Enum.GetValues to the IEnumerable needed by ToDictionary. I suggested an edit to this effect. – Slider345 Oct 09 '12 at 13:42