开发者

If a checkbox is checked how to set a dropdown as a required field in C#

开发者 https://www.devze.com 2023-03-26 12:59 出处:网络
In the ASP.NET MVC 3.5 app. I have a check box, \"Food/Bev\", which is of a boolean type, andI\'d like to know how to manage this:

In the ASP.NET MVC 3.5 app. I have a check box, "Food/Bev", which is of a boolean type, and I'd like to know how to manage this:

If the check box is checked:

  • A dropdown list Caterer becomes a required field.
  • A request cannot be submitted unless the Cat开发者_运维百科erer option is selected from the list.

If the check box is not checked:

  • The Caterer dropdown list is not a required field.

Thank you for your help!


Just do a simple if condition

if this.checkbox.checked && this.mydropdown.selectedindex=-1
  //code / alert that warns the user you must make a selection

You can probably use the ?: operator:

bool b = ((myCheck.Checked && myDropDown.SelectedIndex==-1) ? true : false);

if(b) {
 //stop submit of form as no selection was made
}

Or keep the code short and simple:

 bool b = this.CheckBox1.Checked && this.DropDownList1.SelectedIndex == -1;
 //when the checkbox is not check Response.Write(b); prints false
//when the checkbox IS checked and no item is selected, Response.Write(b); prints true


Add a required field validator for the DropDown, and set Enabled="false" by default. Add an OnCheckChanged event to the CheckBox with AutoPostBack="true", and in the event handler set the enabled state of the validator to the checked state of the CheckBox.


Create a RequiredFieldValidator for the drop down list, but set it to Enabled=false. Then, when the checkbox is checked, call the ValidatorEnable function to enable the validator.

This article is old, but it's information is still relevant: http://msdn.microsoft.com/en-us/library/aa479045.aspx#aspplusvalid_clientside

0

精彩评论

暂无评论...
验证码 换一张
取 消