我有一個包含兩個單選按鈕的表單。一個與下拉菜單相關(guān)聯(lián),另一個與文本框相關(guān)聯(lián)。如果用戶選擇第二個單選按鈕(文本框),我想關(guān)閉下拉菜單所需的消息,因為當(dāng)用戶按下“提交”按鈕時,下拉菜單會顯示一條消息“請選擇一個列表中的項目。”順便說一句,如果我在選擇第二個單選按鈕時禁用下拉菜單,我可以讓它正常工作,但我想知道是否有另一種方法(可能更好),因為當(dāng)你禁用下拉菜單時,它會變灰。截圖:模型:public class EnrollmentModel : Controller{ ... public bool PriceOption { get; set; } [RequiredIf("PriceOption == true")] public string SelectedRatePlan { get; set; } public IEnumerable<SelectListItem> RatePlans { get; set; } [RequiredIf("PriceOption == false")] public string CustomRate { get; set; } ...}看法:@using (Html.BeginForm()){ @Html.AntiForgeryToken() <fieldset> <div class="form-group"> <div class="row"> @Html.Label("Price Option:") </div> </div> <div class="form-group"> <div class="row"> @Html.RadioButtonFor(x => Model.PriceOption, true, htmlAttributes: new { @id = "comed", @class = "col-md-1" }) @Html.Label("Use price from current rate plan") @Html.DropDownListFor(x => Model.SelectedRatePlan, new SelectList(Model.RatePlans, "Value", "Text"), htmlAttributes: new { @class = "form-control", id = "rateplans", style = "width:100px;", required = "Select Rate Plan" }) @Html.ValidationMessageFor(x => Model.SelectedRatePlan, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="row"> @Html.RadioButtonFor(x => Model.PriceOption, false, htmlAttributes: new { @id = "custom", @class = "col-md-1" }) @Html.Label("Enter custom price") @Html.TextBoxFor(x => Model.CustomRate, htmlAttributes: new { @id = "customrate", @class = "form-control", style = "width:100px;" }) @Html.ValidationMessageFor(x => Model.CustomRate, "", new { @class = "text-danger" }) </div>
1 回答

陪伴而非守候
TA貢獻(xiàn)1757條經(jīng)驗 獲得超8個贊
您需要指定該字段在您的模型中是可選的,因為 bool 不能為 null。添加 ”?” 在“bool”之后或使用“Nullable”而不是“bool”
public bool? PriceOption { get; set; }
該問號表示此屬性可以為空。
在此頁面中,您可以找到如何在單選按鈕上實現(xiàn)更改事件: https ://devdojo.com/tutorials/how-to-detect-radio-box-change-with-jquery
您可以使用以下代碼刪除屬性:
$("#selectElementId").removeAttr("required");
- 1 回答
- 0 關(guān)注
- 148 瀏覽
添加回答
舉報
0/150
提交
取消