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.validate
和 jquery.validate.unobtrusive
檔案。