【发布时间】:2017-03-30 16:40:28
【问题描述】:
我有一个模型,其中包含必需的属性。是否可以对非提交类型的按钮单击进行数据验证。我确实参考了this article 和this one,但并没有解决问题。
这是我的型号代码。
[Required]
[Display(Name = "Number of beds")]
public int Beds { get; set; }
[Required]
[Display(Name = "Number of Inpatient Beds")]
public int InpatientBeds { 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.Beds)
@Html.TextBoxFor(m => m.Beds, new { @class = "form-control", @type = "number"})
@Html.ValidationMessageFor(m => m.Beds)
</div>
<div class="col-md-3">
@Html.LabelFor(m => m.InpatientBeds)
@Html.TextBoxFor(m => m.InpatientBeds, new { @class = "form-control", @type = "number"})
@Html.ValidationMessageFor(m => m.InpatientBeds)
</div>
<div class="col-md-3">
<button type=button class="btn btn-primary" id="btnCalculateScore" > Calculate Score</button>
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-primary" id="btnSaveChanges" data-toggle="modal"><i class="fa fa-share-square-o"></i> Update Status</button>
</div>
</div>
}
还有我的脚本
$('#btnCalculateScore').on('click', function (evt) {
evt.preventDefault();
if ($('#form1').valid()) {
//Do Something.
}
}
验证不起作用,即使字段为空,控件也会进入 if 循环?有什么我想念的吗?这种方法是否还会发出通常在提交按钮事件中发生的验证消息?
编辑:
我添加了一个普通的更新状态按钮,类型为提交,验证工作正常。
我将 id 添加到我的表单中以确保视图是否包含其他表单无关紧要。
【问题讨论】:
-
如果您将按钮类型更改为
type="submit",客户端验证是否有效?我只想知道jquery.validate.unobtrusive在您的代码中有效。 -
@Win 我确实将其更改为提交并使用了 jquery.validate.unobtrusive。但似乎仍然无法正确验证
-
你是否包含了 jquery 库?
-
@CristianSzpisjak 我做到了。否则我会在按钮单击本身时遇到错误。
-
您没有带有
id="form1"的表单 - 您的BeginForm()重载是添加路由值,而不是html 属性。
标签: c# jquery asp.net-mvc data-annotations