MVC5。验证错误出现时如何保持对话框表单大小

时间:2017-04-09 14:10:57

标签: javascript html asp.net asp.net-mvc-5

问题:当用户从列表中编辑项目(以对话框形式)并输入超过允许的符号时,对话框表单会改变它的大小。(发生验证错误后(参见附页)

How it opens in edit mode

After Validation error occurred, form size changed

查看:



@model Maintenance.Models.AppVersion


@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 App Version</h4>
        </div>

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

        <div class="modal-body">
            <div class="form-horizontal">
                <div class="form-group margin-bottom">
                    @Html.LabelFor(model => model.AppVersionDescription, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.AppVersionDescription, new { htmlAttributes = new { @class = "form-control", autofocus = "" } })
                        @Html.ValidationMessageFor(model => model.AppVersionDescription, null, 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")

  }
&#13;
&#13;
&#13;

布局:

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

脚本(显示对话框):

&#13;
&#13;
$(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,
            draggable: true,
            resizable: false,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {

                    $('#myModal').modal('hide');
                    $('#progress').hide();
                    //location.reload();
                    alert(result.message);
            }
        });
        return false;
    });
}
&#13;
&#13;
&#13;

指数:

&#13;
&#13;
@model Maintenance.Models.AppVersionsSearchModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>App Versions</h3>

@using (Html.BeginForm("index", "AppVersions", FormMethod.Get))
{
    <div class="row">
        <div class="form-horizontal">
            <div class="col-lg-3">
                @Html.TextBoxFor(m => m.AppVersion1, new { @class = "form-control", @placeholder = "App Version" })
            </div>
            <div class="col-lg-3" style="vertical-align: bottom;">
                <input name="SearchButton" type="submit" value="Search" class="btn btn-primary" />
            </div>
        </div>
    </div>

    <div class="grid-control grid-control-app-version">
        @{
            var grid = new WebGrid(canPage: true,
            rowsPerPage: Model.PageSize,
            canSort: true,
            ajaxUpdateContainerId: "grid"
            );
            grid.Bind(Model.AppVersions, rowCount: Model.TotalRecords, autoSortAndPage: false);
            grid.Pager(WebGridPagerModes.All);
            @grid.GetHtml(
                fillEmptyRows: false,
                tableStyle: "webgrid-table webgrid-table-app-version",
                headerStyle: "webgrid-header",
                footerStyle: "webgrid-footer",
                alternatingRowStyle: "webgrid-alternating-row",
                mode: WebGridPagerModes.All,
                columns: grid.Columns(
                    grid.Column(header: "Action", canSort: false, style: "action",
                        format: @<text>
                        @Html.Raw("<a data-modal='' href='/AppVersions/Details/" + item.AppVersion1 + "' id='" + item.AppVersion1 + "' title='Detail'> <span class='glyphicon glyphicon-list-alt'> </span> </a>")
                        @Html.Raw("<a data-modal='' href='/AppVersions/Edit/" + item.AppVersion1 + "' id='" + item.AppVersion1 + "' title='Edit'> <span class='glyphicon glyphicon-edit'> </span> </a>")
                        @Html.Raw("<a data-modal='' href='/AppVersions/Delete/" + item.AppVersion1 + "' id='" + item.AppVersion1 + "' title='Delete'> <span class='glyphicon glyphicon-trash'> </span> </a>")
                        </text>
                        ),
                    grid.Column(columnName: "AppVersion1", header: Sorter("AppVersion1", "App Version", grid), style: "AppVersion-AppVersion1"),
                    grid.Column(columnName: "AppVersionDescription", header: Sorter("AppVersionDescription", "App Version Description", grid), style: "AppVersion-AppVersionDescription"),
                    grid.Column(columnName: "CreateDate", header: Sorter("CreateDate", "Creation Date", grid), style: "AppVersion-CreateDate")
                    )
                )
            ;
        }
    </div>
}

<div class="row">
    <div class="form-horizontal">
        <div class="col-lg-3">
           @Html.ActionLink("Create New App Version", "Create", null, htmlAttributes: new { @class = "modal-link btn btn-primary",  data_target = "#myModal", data_toggle = "myModal" })
        </div>
    </div>
</div>

@functions {
    public static string Sorter(string columnName, string columnHeader, WebGrid grid)
    {
        return string.Format("{0} {1}", columnHeader, grid.SortColumn == columnName ?
            grid.SortDirection == SortDirection.Ascending ? "▲" :
                "▼" : string.Empty);
    }
}

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

<script type="text/javascript">
    $(function () {
        $('th a, tfoot a').click(function () {
            $('form').attr('action', $(this).attr('href')).submit();
            return false;
        });
    });
</script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

如果你看一下模态中的线条。

<div class="col-md-8">
                        @Html.EditorFor(model => model.AppVersionDescription, new { htmlAttributes = new { @class = "form-control", autofocus = "" } })
                        @Html.ValidationMessageFor(model => model.AppVersionDescription, null, new { @class = "field-validation-error-tooltip" })
</div>

当您运行代码时,右键单击模态输入框并检查生成的html。您将看到EditorFor模板和ValidationMessageFor成为一行,因为Validation被添加到a。中。

您可以选择,您可以设置模态宽度的样式,并将最大宽度类设置为您的EditorFor条目到下面一行的换行。

或者

您可以将ValidationMessageFor放在Current块之外并尝试。