0

I have a basic question about ASP.NET MVC dropdown list. I have the following dropdownlist

Select Color - -->option 1 Value:"-1"

Red -->option 2 Value: "Red"

Green -->option 3 Value:"Green"

Blue -->option 4 Value:"Blue"

My view model is as follows:

public class ViewModel
{    
  public List<SelectListItem> ColorList {get; set;}

  public string Color {get; set;}

}

If nothing was pre-selected then while loading the dropdown list I append a value of "-1" and add Text "- Select Color -" and set it as a selected option. Doing this I have to write custom validation if the dropdownlist is required to check for "-1" or if it's not required and I have to store null in the database I have to strip off the "-1" before saving. This seems to be a hassle for me.

I was wondering if there is a standard way to set values on a dropdown when nothing is selected and a standard way of validating them?

Sparky
  • 98,165
  • 25
  • 199
  • 285
user1527762
  • 927
  • 4
  • 13
  • 29
  • *"I was wondering if there is a standard way to set values on a dropdown when nothing is selected and a standard way of validating them?"* ~ Yes, change the `-1` value into an empty string... that's how the plugin works with `select` by default. If you're stuck with `-1`, then you'll need to write your own custom rule. – Sparky Mar 24 '16 at 14:49
  • See this answer: http://stackoverflow.com/a/6218499/594235 – Sparky Mar 24 '16 at 14:50
  • 1
    @Sparky - this is an MVC problem, not strictly an jquery.validation issue, as MVC overrides the default behavior of jquery.validation. Although, the framework does insert an empty string when the selected value is null – Erik Funkenbusch Mar 24 '16 at 15:58

1 Answers1

3

The answer is actually very simple, and is built into MVC and the Microsoft unobtrusive validation.

If the selected value is null, then the value of the "option" field is displayed as the default. In other words, you do something like this:

Html.DropDownListFor(x => x.Color, Model.ColorList, "Select Color...")

So, when Model.Color is null (make sure it's a nullable value), it will show "Select Color..." or whatever you want to put there.

If Model.Color has a [Required] validation, then it will ensure that you select a value before the model validates.

In effect, you are fighting the framework by trying to do this manually.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291