JQuery 中的模型验证

在需要使用 Jquery 确保模型验证的情况下,可以使用 .valid() 函数。

模型类字段

[Required]
[Display(Name = "Number of Hospitals")]
public int Hospitals{ get; set; }
[Required]
[Display(Name = "Number of Beds")]
public int Beds { get; set; }

查看代码

@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))
{

<div class="divPanel">
  <div class="row">
    <div class="col-md-3">                
            @Html.LabelFor(m => m.Hospitals)
            @Html.TextBoxFor(m => m.Hospitals, new { @class = "form-control", @type = "number"})
            @Html.ValidationMessageFor(m => m.Hospitals)

    </div>
    <div class="col-md-3">

            @Html.LabelFor(m => m.Beds)
            @Html.TextBoxFor(m => m.Beds, new { @class = "form-control", @type = "number"})
            @Html.ValidationMessageFor(m => m.Beds)
    </div>
<div class="col-md-3">             
        <button type=button  class="btn btn-primary" id="btnCalculateBeds"> Calculate Score</button>
    </div>
 </div>

  </div>
 }

验证检查脚本。

$('#btnCalculateBeds').on('click', function (evt) {
evt.preventDefault();

if ($('#form1').valid()) {
//Do Something.
}
}

确保解决方案中存在 jquery.validatejquery.validate.unobtrusive 文件。