Jquery 绑定单选按钮时不显眼的验证
Jquery unobstrusive validation while binding radio button
我有一个表单要求用户 select Yes or No
基于某些 questions.Intitally none 选项将 selected.If 用户点击 save
没有 select 选项验证的按钮应该显示
<div>
<label for="IsSourceCodeCollected" class=" control-label">
Question 1
</label>
</div>
<div>
<label style="width:100px">
@Html.RadioButtonFor(m => m.StudentProjectApprovalTrainer.IsSourceCodeCollected, true, new { @class = "minimal sourceCodeCollected" })
YES
</label>
<label style="width:100px">
@Html.RadioButtonFor(m => m.StudentProjectApprovalTrainer.IsSourceCodeCollected, false, new { @class = "minimal sourceCodeCollected" })
NO
</label>
</div>
@Html.ValidationMessageFor(m => m.StudentProjectApprovalTrainer.IsSourceCodeCollected)
<button type="submit" id="btnSubmit" class="btn btn-info pull-left ">
<i class="fa fa-save"></i>
Save
</button>
型号
[Required(ErrorMessage = "Please select this")]
public bool IsSourceCodeCollected { get; set; }
Javascript
$(document).on("click", "#btnSubmit", function () {
var form = $("#frmAdd");
if (form.valid()) {
alert("hai");
};
return false;
});
当我在没有 selecting 的情况下单击保存按钮时,会显示 Yes or No
提示,这意味着表单有效。
我该如何解决这种情况??
您的 属性 是 typeof bool
,它必须始终有一个值(添加 [Required]
属性不是必需的,除非您想要特定的错误消息)。因为它的值是 true
或 false
,所以当视图第一次呈现时,你的一个单选按钮将总是被选中(并且不可能 'un-select' 两者)所以模型总是有效。
如果您希望选项将两个按钮都显示为未选中状态,并在未选中时显示验证错误,则需要将 属性 更改为 nullable
。
[Required(ErrorMessage = "Please select this")]
public bool? IsSourceCodeCollected { get; set; }
我有一个表单要求用户 select Yes or No
基于某些 questions.Intitally none 选项将 selected.If 用户点击 save
没有 select 选项验证的按钮应该显示
<div>
<label for="IsSourceCodeCollected" class=" control-label">
Question 1
</label>
</div>
<div>
<label style="width:100px">
@Html.RadioButtonFor(m => m.StudentProjectApprovalTrainer.IsSourceCodeCollected, true, new { @class = "minimal sourceCodeCollected" })
YES
</label>
<label style="width:100px">
@Html.RadioButtonFor(m => m.StudentProjectApprovalTrainer.IsSourceCodeCollected, false, new { @class = "minimal sourceCodeCollected" })
NO
</label>
</div>
@Html.ValidationMessageFor(m => m.StudentProjectApprovalTrainer.IsSourceCodeCollected)
<button type="submit" id="btnSubmit" class="btn btn-info pull-left ">
<i class="fa fa-save"></i>
Save
</button>
型号
[Required(ErrorMessage = "Please select this")]
public bool IsSourceCodeCollected { get; set; }
Javascript
$(document).on("click", "#btnSubmit", function () {
var form = $("#frmAdd");
if (form.valid()) {
alert("hai");
};
return false;
});
当我在没有 selecting 的情况下单击保存按钮时,会显示 Yes or No
提示,这意味着表单有效。
我该如何解决这种情况??
您的 属性 是 typeof bool
,它必须始终有一个值(添加 [Required]
属性不是必需的,除非您想要特定的错误消息)。因为它的值是 true
或 false
,所以当视图第一次呈现时,你的一个单选按钮将总是被选中(并且不可能 'un-select' 两者)所以模型总是有效。
如果您希望选项将两个按钮都显示为未选中状态,并在未选中时显示验证错误,则需要将 属性 更改为 nullable
。
[Required(ErrorMessage = "Please select this")]
public bool? IsSourceCodeCollected { get; set; }