Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating required selection in DropDownList

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.

like image 268
Ladislav Mrnka Avatar asked Jan 12 '11 18:01

Ladislav Mrnka


People also ask

How do you validate a drop down list?

Select the cell in the worksheet where you want the drop-down list. Go to the Data tab on the Ribbon, then click Data Validation. On the Settings tab, in the Allow box, click List. If it's OK for people to leave the cell empty, check the Ignore blank box.

How to validate the select option in JavaScript?

To validate select box with JavaScript, we check if the select element's value property is set. to add a select drop down. const select = document. getElementById("select"); if (select.

How to validate dynamic DropDown in JavaScript?

function validateRadio() { var flag = false; $('#<%=RadioButtonList1. ClientID%> input'). each(function(){ if($(this).is(":checked")) flag = true; }); return flag; } function validateDropList() { if ($('#<%=DropDownList1.


1 Answers

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.

like image 179
Darin Dimitrov Avatar answered Sep 23 '22 13:09

Darin Dimitrov