Validating required selection in DropDownList
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.
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, 2022Comments
-
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
containsIEnumerable<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 over 13 yearsNice, I completely misunderstood that overload. Thanks.
-
Akira Yamamoto about 10 yearsThis does not validate on client side :(
-
Legends over 7 yearsThis works for me ... perfect. So, instead of adding the default value directly to the model, you add it directly via the overload.
-
Ratan over 7 yearsThis worked for me too, but trying to figure out why? Any reason why this works and the other doesn't?