Search code examples
jqueryasp.net-mvcasp.net-mvc-4jquery-validateunobtrusive-validation

ASP.NET MVC DropdownList setting default when nothing selected


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?


Solution

  • 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.