如何为下拉列表关闭所需的消息?

问题描述 投票:0回答:1

我有一个表单包含两个单选按钮。一个与下拉列表相关联,另一个与文本框相关联。如果用户选择第二个单选按钮(文本框),我想关闭下拉列表所需的消息,因为当用户按下“提交”按钮时,下拉列表会显示一条消息“请选择一个列表中的项目。“

顺便说一句,如果我在选择第二个单选按钮时禁用了下拉菜单,但是我想知道是否有另一种方式(可能更好),我让它正常工作,因为当您禁用下拉菜单时,它会将其更改为灰色。

截图:

enter image description here enter image description here

模型:

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")
        &nbsp;
        &nbsp;
        &nbsp;
        @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")
        &nbsp;
        &nbsp;
        &nbsp;
        @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>
    </div>
    <div class="form-group">
      <div class="row">
        <div class="col-md-8">
          <input type="button" value="Cancel" class="btn btn-link" onclick="location.href = '@Url.Action("Index", "Home")';" />
          &nbsp;
          <button type="submit" value="Save" class="btn btn-primary">Submit</button>
        </div>
      </div>
    </div>
  </fieldset>
}
c# jquery html asp.net-mvc asp.net-core
1个回答
1
投票

您需要在模型中指定该字段是可选的,因为bool不能为null。添加“?”在“bool”之后或使用“Nullable”而不是“bool”

 public bool? PriceOption { get; set; }

该问号表示此属性可以为null。

在此页面中,您可以找到如何在单选按钮上实现更改事件:https://devdojo.com/tutorials/how-to-detect-radio-box-change-with-jquery

您可以使用以下代码删除属性:

$("#selectElementId").removeAttr("required");
© www.soinside.com 2019 - 2024. All rights reserved.