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.
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.
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.
function validateRadio() { var flag = false; $('#<%=RadioButtonList1. ClientID%> input'). each(function(){ if($(this).is(":checked")) flag = true; }); return flag; } function validateDropList() { if ($('#<%=DropDownList1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With