Validating required selection in DropDownList

21,177

How about this:

[Required]
public int? Processor { get; set; }

And then:

<%= Html.DropDownListFor(
    x => x.Processor, Model.Processors, "-- select processor --"
) %>

And in your POST action

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        // the model is valid => you can safely use model.Processor.Value here:
        int processor = model.Processor.Value;
        // TODO: do something with this value
    }
    ...
}

And now you no longer need to manually add the noSelection item. Just use the proper DropDownListFor overload.

Share:
21,177
Ladislav Mrnka
Author by

Ladislav Mrnka

I'm originally from Prague but I currently live in London. In the past I worked for Prime Video on video players and tools to test video playback but I decided to take leap of faith and search for a new challenges outside of Amazon. I found that at The Trade Desk where I work on digital advertising challenges.

Updated on July 09, 2022

Comments

  • Ladislav Mrnka
    Ladislav Mrnka almost 2 years

    My view model defines property which has to be displayed as combo box. Property definition is:

    [Required]
    public int Processor { get; set; }
    

    I'm using DropDownListFor to render combo box:

    <%=Html.DropDownListFor(r => r.Processor, Model.Processors, Model.Processor)%>
    

    Model.Processors contains IEnumerable<SelectListItem> with one special item defined as:

    var noSelection = new SelectListItem
      {
        Text = String.Empty,
        Value = "0"
      };
    

    Now I need to add validation to my combo box so that user must select different value then 'noSelection'. I hoped for some configuration of RequiredAttribute but it doesn't have default value setting.

  • Ladislav Mrnka
    Ladislav Mrnka over 13 years
    Nice, I completely misunderstood that overload. Thanks.
  • Akira Yamamoto
    Akira Yamamoto about 10 years
    This does not validate on client side :(
  • Legends
    Legends over 7 years
    This works for me ... perfect. So, instead of adding the default value directly to the model, you add it directly via the overload.
  • Ratan
    Ratan over 7 years
    This worked for me too, but trying to figure out why? Any reason why this works and the other doesn't?