jquery - 如何防止模式弹出窗口在出现验证错误时提交表单

标签 jquery razor twitter-bootstrap-3 modal-dialog asp.net-mvc-5

我正在开发一个 asp.net mvc5 Web 应用程序,并且我正在使用 Bootstrap 和 WebGrid 实现 CRUD 操作。

现在我的创建操作方法如下所示:-

 [HttpGet]
        public ActionResult Create()
        {
            var phone = new Phone();
            return PartialView("Create", phone);
        }


        // POST: /Phone/Create
        [HttpPost]
        public JsonResult Create(Phone phone)
        {
            if (ModelState.IsValid)
            {
                db.Phones.Add(phone);
                db.SaveChanges();
                return Json(new { success = true });
            }
            return Json(phone, JsonRequestBehavior.AllowGet);
        }

索引 View 有一个创建按钮,可以打开弹出窗口:-

 <div class="pull-right col-lg-1">   
                <a class="btn btn-success" data-modal="" href="/Phone/Create" id="btnCreate">
                     <span class="glyphicon glyphicon-plus"></span>      
                </a>
            </div>
<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>
        </div>
    </div>
</div>

@section scripts{
    @Scripts.Render("~/scripts/appjs/phones.js")
}

phones.js 是:-

  $(function () {
        $.ajaxSetup({ cache: false });
        $("a[data-modal]").on("click", function (e) {        
            $('#myModalContent').load(this.href, function () {
                $('#myModal').modal({
                    keyboard: true
                }, 'show');

                bindForm(this);
            });
            return false;
        });


    });

    function bindForm(dialog) {
        $('form', dialog).submit(function () {
            $('#progress').show();
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.success) {
                        $('#myModal').modal('hide');
                        $('#progress').hide();
                        location.reload();
                    } else {
                        $('#progress').hide();
                        $('#myModalContent').html(result);
                        bindForm();
                    }
                }
            });
            return false;
        });
    }

创建 View :-

  @model MvcBootstrapCrud.Models.Phone

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 class="modal-title">Add New Phone</h3>
    </div>


    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="modal-body">

            <div class="form-horizontal">
                <div class="form-group">
                    @Html.LabelFor(m => Model.Model, new { @class = "control-label col-sm-3" })
                    <div class="col-sm-9">
                        @Html.TextBoxFor(m => m.Model, new { @class = "form-control required" })
                        <div>
                            @Html.ValidationMessageFor(m => m.Model)
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m => Model.Company, new { @class = "control-label col-sm-3" })
                    <div class="col-sm-9">
                        @Html.TextBoxFor(m => m.Company, new { @class = "form-control required" })
                        <div>
                            @Html.ValidationMessageFor(m => m.Company)
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m => Model.Price, new { @class = "control-label col-sm-3" })
                    <div class="col-sm-9">
                        @Html.TextBoxFor(m => m.Price, new { @class = "form-control required" })
                        <div>
                            @Html.ValidationMessageFor(m => m.Price)
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <span id="progress" class="text-center" style="display: none;">
                <img src="/images/wait.gif" alt="wiat" />
                Wait..
            </span>

            <input class="btn btn-primary" type="submit" value="Save" />
            <button class="btn btn-warning" data-dismiss="modal">Close</button>
        </div>
    }
    <script>
        $("form").removeData("validator");
        $("form").removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse("form");
    </script>

和电话型号类:-

public class Phone
    {
        [Display(Name = "ID")]
        [Key]
        public int PhoneId { get; set; }

        [Required]
        [Display(Name = "Model Name")]
        public string Model { get; set; }

        [Required]
        [Display(Name = "Company Name")]
        public string Company { get; set; }

        [Required]
        [Display(Name = "Price")]
        [DataType(DataType.Currency)]
        public decimal Price { get; set; }
    }

我面临的问题是,当显示创建模式弹出表单并且用户将必填字段留空时,该字段旁边将显示验证错误(如 [Required] 数据注释中所定义)。但是当用户单击“保存”按钮时,验证错误不会阻止弹出窗口提交表单,即使显示验证错误,也会调用“创建后”操作方法。所以有人可以对此提出建议吗? 谢谢

最佳答案

根据documentation如果存在任何验证错误,调用 $('form').valid() 应返回 false,但是在运行一些测试后,有时会抛出 Uncaught SyntaxError: Unexpected token u (JSON.parse(data) 的结果,其中 dataundefined)。不知道为什么这种情况只偶尔发生。但是,您可以验证每个单独的元素并阻止 ajax 调用(如果有无效的元素)

$('form', dialog).submit(function () {
  var isValid = true; // assume all OK
  $('form').validate(); // perform validation on the form
  $('input[type="text"]').each(function (index, item) { // could change selector to suit e.g $('input, textarea').each(..            
    if (!$(this).valid()) {
      isValid = false; // signal errors
      return false; // break out of loop   
    }
  })
  if (!isValid) {
    return false; // exit
  }
  // Good to submit
  $('#progress').show();
    $.ajax({
      url: this.action,
      .....

关于jquery - 如何防止模式弹出窗口在出现验证错误时提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27935143/

相关文章:

html - 如何使用 col-sm 内联?

css - 为什么导航栏和屏幕右边缘之间留有空间?

jquery - jQuerywrapper和wrapAll之间的区别

Javascript:如何检查网址是否存在?

jquery - 下拉菜单关闭问题

c# - 如何在单元测试中检查模型属性

c# - 在 MVC/Razor 中,如何获取多个复选框的值并将它们全部传递给 Controller ​​?

javascript - 使用网格 ID 隐藏剑道网格工具栏

c# - 找不到 ASP.NET View

javascript - Bootstrap Modal - 设置远程路径并以编程方式打开