MVC5 asp.net验证后,对话框形式出现故障

时间:2017-04-16 11:37:10

标签: javascript jquery twitter-bootstrap asp.net-mvc-5

MVC5 asp.net验证后,对话框表格中断

1。 _Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Moving Pro Services</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
</head>
    <body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        @if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("Moving Pro Services", "Index", "Home", new {area = ""}, new {@class = "navbar-brand"})
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Services <span class="caret"></span></a>
                            <ul class="dropdown-menu" role="menu">
                                <li>@Html.ActionLink("Companies", "Index", "Companies")</li>
                                <li>@Html.ActionLink("App Versions", "Index", "AppVersions")</li>
                                @if (User.Identity.IsAuthenticated)
                                {
                                    if (User.IsInRole("Administrator"))
                                    {
                                        <li>@Html.ActionLink("Create User", "Register", "Account")</li>
                                    }
                                }
                            </ul>
                        </li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                    @Html.Partial("_LoginPartial")
                </div>
            </div>
        }
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr/>
        <footer>
            <p>&copy; @DateTime.Now.Year - Moving Pro Services</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

    <div id='myModal' class='modal fade in'>
        <div class="modal-dialog">
            <div class="modal-content">
                <div id='myModalContent'></div>
            </div>
        </div>
    </div>

    </body>
</html>

2。模型

    //------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Maintenance.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class Company
    {
        public int ID { get; set; }
        [Display(Name = "Company Name")]
        [StringLength(100)]
        public string CompanyName { get; set; }
        [Display(Name = "Server Alias")]
        [StringLength(100)]
        public string ServerAlias { get; set; }
        [Display(Name = "Server Name")]
        public string ServerName { get; set; }
        [Display(Name = "Database Name")]
        public string DatabaseName { get; set; }
        [Display(Name = "Email Database Name")]
        public string EmailDatabaseName { get; set; }
        [Display(Name = "Integrated Security")]
        public bool IntegratedSecurity { get; set; }
        [Display(Name = "User Name")]
        public string UserName { get; set; }
        [Display(Name = "PWD")]
        public string Password { get; set; }
        [Display(Name = "App Key")]
        public string AppKey { get; set; }
        [StringLength(20)]
        [Display(Name = "App Version")]
        public string AppVersion { get; set; }
        [Display(Name = "In Home Estimate")]
        public bool InHomeEstimate { get; set; }
        [Display(Name = "Foreman Inventory")]
        public bool ForemanInventory { get; set; }
        [Display(Name = "Docs")]
        public bool Documents { get; set; }
        [Display(Name = "Storage Scan In")]
        public bool StorageScanIn { get; set; }
        [Display(Name = "Storage Scan Out")]
        public bool StorageScanOut { get; set; }
        [Display(Name = "Scan At Delivery")]
        public bool ScanAtDelivery { get; set; }
        [Display(Name = "Amazon Rds")]
        public bool AmazonRds { get; set; }
        [Display(Name = "Amazon Region")]
        [StringLength(20)]
        public string AmazonRegion { get; set; }
        [Display(Name = "Amazon Identifier")]
        public string AmazonIdentifier { get; set; }
        [Display(Name = "App Version")]
        public virtual AppVersion AppVersion1 { get; set; }
    }
}

第3。控制器

        // GET: Companies/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Company company = _db.Companies.Find(id);
            if (company == null)
            {
                return HttpNotFound();
            }
            ViewBag.AppVersion = new SelectList(_db.AppVersions, "AppVersion1", "AppVersionDescription", company.AppVersion);
            return PartialView(company);
        }

        // POST: Companies/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,CompanyName,ServerAlias,ServerName,DatabaseName,EmailDatabaseName,IntegratedSecurity,AppKey,AppVersion,InHomeEstimate,ForemanInventory,Documents,StorageScanIn,StorageScanOut,ScanAtDelivery,AmazonRds,AmazonRegion,AmazonIdentifier")] Company company)
        {
            if (ModelState.IsValid)
            {
                _db.Entry(company).State = EntityState.Modified;
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.AppVersion = new SelectList(_db.AppVersions, "AppVersion1", "AppVersionDescription", company.AppVersion);
            return PartialView(company);
        }

4。图

@model Maintenance.Models.Company

@using (Html.BeginForm())
{
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title">Edit Company</h4>
        </div>

        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.ID)

        <div class="modal-body">
            <div class="form-horizontal">
                <div class="form-group margin-small">
                    @Html.LabelFor(model => model.CompanyName, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.CompanyName, new { htmlAttributes = new { @class = "form-control", autofocus = "" } } )
                        @Html.ValidationMessageFor(model => model.CompanyName, "", new { @class = "field-validation-error-tooltip" })
                    </div>
                </div>

                <div class="form-group margin-small">
                    @Html.LabelFor(model => model.ServerAlias, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.ServerAlias, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ServerAlias, "", new { @class = "field-validation-error-tooltip" })
                    </div>
                </div>

                <div class="form-group margin-small">
                    @Html.LabelFor(model => model.ServerName, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.ServerName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.ServerName, "", new { @class = "field-validation-error-tooltip" })
                    </div>
                </div>

                <div class="form-group margin-small">
                    @Html.LabelFor(model => model.DatabaseName, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.DatabaseName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.DatabaseName, "", new { @class = "field-validation-error-tooltip" })
                    </div>
                </div>

                <div class="form-group margin-small">
                    @Html.LabelFor(model => model.EmailDatabaseName, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.EmailDatabaseName, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.EmailDatabaseName, "", new { @class = "field-validation-error-tooltip" })
                    </div>
                </div>

                <div class="form-group margin-small">
                    <div class="col-md-5">
                        <div class="checkbox control-checkbox">
                            @Html.EditorFor(model => model.IntegratedSecurity, new { htmlAttributes = new { @class = "input-control-checkbox" } })
                            @Html.ValidationMessageFor(model => model.IntegratedSecurity, "", new { @class = "field-validation-error-tooltip" })
                        </div>
                    </div>
                    @Html.LabelFor(model => model.IntegratedSecurity, htmlAttributes: new { @class = "control-label col-md-7 control-label-checkbox" })
                </div>

                <div class="form-group margin-small">
                    @Html.LabelFor(model => model.AppKey, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.AppKey, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.AppKey, "", new { @class = "field-validation-error-tooltip" })
                    </div>
                </div>

                <div class="form-group margin-small">
                    @Html.LabelFor(model => model.AppVersion, "App Version", htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.DropDownList("AppVersion", null, htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.AppVersion, "", new { @class = "field-validation-error-tooltip" })
                    </div>
                </div>

                <div class="form-group margin-small">
                    <div class="col-md-5">
                        <div class="checkbox control-checkbox">
                            @Html.EditorFor(model => model.InHomeEstimate, new { htmlAttributes = new { @class = "input-control-checkbox" } })
                            @Html.ValidationMessageFor(model => model.InHomeEstimate, "", new { @class = "field-validation-error-tooltip" })
                        </div>
                    </div>
                    @Html.LabelFor(model => model.InHomeEstimate, htmlAttributes: new { @class = "control-label col-md-7 control-label-checkbox" })
                </div>

                <div class="form-group margin-small">
                    <div class="col-md-5">
                        <div class="checkbox control-checkbox">
                            @Html.EditorFor(model => model.ForemanInventory, new { htmlAttributes = new { @class = "input-control-checkbox" } })
                            @Html.ValidationMessageFor(model => model.ForemanInventory, "", new { @class = "field-validation-error-tooltip" })
                        </div>
                    </div>
                    @Html.LabelFor(model => model.ForemanInventory, htmlAttributes: new { @class = "control-label col-md-7 control-label-checkbox" })
                </div>

                <div class="form-group margin-small">
                    <div class="col-md-5">
                        <div class="checkbox control-checkbox">
                            @Html.EditorFor(model => model.Documents, new { htmlAttributes = new { @class = "input-control-checkbox" } })
                            @Html.ValidationMessageFor(model => model.Documents, "", new { @class = "field-validation-error-tooltip" })
                        </div>
                    </div>
                    @Html.LabelFor(model => model.Documents, htmlAttributes: new { @class = "control-label col-md-7 control-label-checkbox" })
                </div>

                <div class="form-group margin-small">
                    <div class="col-md-5">
                        <div class="checkbox control-checkbox">
                            @Html.EditorFor(model => model.StorageScanIn, new { htmlAttributes = new { @class = "input-control-checkbox" } })
                            @Html.ValidationMessageFor(model => model.StorageScanIn, "", new { @class = "field-validation-error-tooltip" })
                        </div>
                    </div>
                    @Html.LabelFor(model => model.StorageScanIn, htmlAttributes: new { @class = "control-label col-md-7 control-label-checkbox" })
                </div>

                <div class="form-group margin-small">
                    <div class="col-md-5">
                        <div class="checkbox control-checkbox">
                            @Html.EditorFor(model => model.StorageScanOut, new { htmlAttributes = new { @class = "input-control-checkbox" } })
                            @Html.ValidationMessageFor(model => model.StorageScanOut, "", new { @class = "field-validation-error-tooltip" })
                        </div>
                    </div>
                    @Html.LabelFor(model => model.StorageScanOut, htmlAttributes: new { @class = "control-label col-md-7 control-label-checkbox" })
                </div>

                <div class="form-group margin-small">
                    <div class="col-md-5">
                        <div class="checkbox control-checkbox">
                            @Html.EditorFor(model => model.ScanAtDelivery, new { htmlAttributes = new { @class = "input-control-checkbox" } })
                            @Html.ValidationMessageFor(model => model.ScanAtDelivery, "", new { @class = "field-validation-error-tooltip" })
                        </div>
                    </div>
                    @Html.LabelFor(model => model.ScanAtDelivery, htmlAttributes: new { @class = "control-label col-md-7 control-label-checkbox" })
                </div>

                <div class="form-group margin-small">
                    <div class="col-md-5">
                        <div class="checkbox control-checkbox">
                            @Html.EditorFor(model => model.AmazonRds, new { htmlAttributes = new { @class = "input-control-checkbox" } })
                            @Html.ValidationMessageFor(model => model.AmazonRds, "", new { @class = "field-validation-error-tooltip" })
                        </div>
                    </div>
                    @Html.LabelFor(model => model.AmazonRds, htmlAttributes: new { @class = "control-label col-md-7 control-label-checkbox" })
                </div>

                <div class="form-group margin-small">
                    @Html.LabelFor(model => model.AmazonRegion, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.AmazonRegion, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.AmazonRegion, "", new { @class = "field-validation-error-tooltip" })
                    </div>
                </div>

                <div class="form-group margin-small">
                    @Html.LabelFor(model => model.AmazonIdentifier, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.AmazonIdentifier, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.AmazonIdentifier, "", new { @class = "field-validation-error-tooltip" })
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <input class="btn btn-primary" type="submit" value="Save changes" id="approve-btn" />
            <button class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        $(function () {
            $("form input").tooltipValidation({
                placement: "right"
            });
        });
    </script>
}

显示对话框的脚本

$(function () {
    $.ajaxSetup({ cache: false });

    $(document).on("click", ".modal-link", function (e) {
        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal
                (
                {
                    keyboard: true
                }, 'show'
                );
            bindForm(this);
        });
        return false;
    });

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

    $(window.document).on('shown.bs.modal', '.modal', function () {
        window.setTimeout(function () {
            $('[autofocus]', this).focus();
        }.bind(this), 100);
    });
});

function bindForm(dialog) {
    $('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
        }
        $('#progress').show();
        $.ajax({
            url: this.action,
            modal: true,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                $('#myModal').modal('hide');
                $('#progress').hide();
                location.reload();
                alert(result.message);
            }
        });
        return false;
    });
}

问题

当我为Edit Company调用对话框表单时,我得到Image1上的对话框表单。 验证后$('form')。validate(); //在表单上执行验证 我得到了Image2上的对话框。请帮我理解我错了什么?

Image1

Image2

1 个答案:

答案 0 :(得分:0)

在控制器中 public ActionResult Edit([Bind(Include = ....)Company company)

需要使用return View(公司);而不是返回PartialView(公司)