绑定单选按钮时Jquery不显眼的验证

时间:2016-02-16 06:31:27

标签: asp.net-mvc-4 binding radio-button jquery-validate

我有一个表单,要求用户根据一些问题选择Yes or No。在没有选项的情况下,如果用户点击save按钮而不选择选项,则应显示

 <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;
});

当我单击保存按钮而未选择Yes or No时,会显示警告,表示表单有效。

我该如何解决这个问题??

1 个答案:

答案 0 :(得分:1)

您的属性是bool类型,必须始终具有值(除非您需要特定的错误消息,否则无需添加[Required]属性)。由于其值为truefalse,因此在首次呈现视图时始终会选择其中一个单选按钮(并且无法选择&#39;取消选择&#39;两者)所以模型总是有效的。

如果您希望选项将两个按钮都显示为未选中,并且如果未选中则显示验证错误,则需要将该属性更改为nullable

[Required(ErrorMessage = "Please select this")]        
public bool? IsSourceCodeCollected { get; set; }