我有一个包含两个单选按钮的表单。一个与一个下拉列表关联,另一个与一个文本框关联。如果用户选择第二个单选按钮(文本框),那么我想关闭该下拉菜单所需的消息,因为当用户按下“提交”按钮时,该下拉列表会显示一条消息“请选择一个列表中的项目。”
顺便说一句,如果我在选择第二个单选按钮时仅禁用了下拉菜单,但我想知道是否还有另一种方法(也许更好),因为当您禁用下拉菜单时,它会更改它变灰了。
屏幕截图:
型号:
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>
</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")';" />
<button type="submit" value="Save" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</fieldset>
}
答案 0 :(得分:1)
您需要指定该字段在模型中是可选的,因为bool不能为null。 加“?”在“布尔”之后或使用“可空”而不是“布尔”
public bool? PriceOption { get; set; }
该问号表示此属性可以为空。
在此页面中,您可以找到如何在单选按钮上实现更改事件: https://devdojo.com/tutorials/how-to-detect-radio-box-change-with-jquery
,您可以使用以下代码删除属性:
$("#selectElementId").removeAttr("required");