【问题标题】:Client side Data Annotation validation on a button click using Jquery使用Jquery单击按钮进行客户端数据注释验证
【发布时间】: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 循环?有什么我想念的吗?这种方法是否还会发出通常在提交按钮事件中发生的验证消息?

编辑:

  1. 我添加了一个普通的更新状态按钮,类型为提交,验证工作正常。

  2. 我将 id 添加到我的表单中以确保视图是否包含其他表单无关紧要。

【问题讨论】:

  • 如果您将按钮类型更改为type="submit",客户端验证是否有效?我只想知道jquery.validate.unobtrusive 在您的代码中有效。
  • @Win 我确实将其更改为提交并使用了 jquery.validate.unobtrusive。但似乎仍然无法正确验证
  • 你是否包含了 jquery 库?
  • @CristianSzpisjak 我做到了。否则我会在按钮单击本身时遇到错误。
  • 您没有带有id="form1" 的表单 - 您的BeginForm() 重载是添加路由值,而不是html 属性。

标签: c# jquery asp.net-mvc data-annotations


【解决方案1】:

我遇到了同样的问题,这似乎为我解决了。

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

在查看页面源代码时,此代码不会将 ID Form1 附加到您的表单。因此,您的验证将不会发生,因为找不到 id form1 的表单。

相反,假设您的操作是一个帖子,并且您将数据保存在 Action Method Save 和控制器 Bed 中,您可以将表单编辑为

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

这会将 id 参数附加到您的表单(您可以使用 ViewPageSource 检查),它应该可以工作。可能有更好的解决方案,但这对我来说可以正常工作,没有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多