MVC5 Ajax.Begin表单,清除/重置BS模态表单

时间:2015-11-30 17:21:53

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

我正在尝试在关闭它时重置我的引导模态窗体,但似乎没有任何工作。我希望能够在提交表单或关闭模式后清除字段并重置模型验证消息。

我已经用Google搜索并尝试了所有内容,但它似乎无法正常工作......所以请一位我迫切需要帮助!

可能是一些遗失的参考文献吗?我正在使用标准的Visual Stusio MVC应用程序模板。

这是我的代码:

主要观点:

 @model CBA.Models.Application.MainRegisterViewModel

    @{
        ViewBag.Title = "MainRegister";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }



    <h2>Users</h2>

    <hr />

    <div class="row">
        <div class="col-md-12">
            <button class="btn btn-default" id="ButtonNewUser">New User</button>
            <button class="btn btn-default" id="ButtonNewCompany">New Company</button>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover">
                ...
            </table>
        </div>
    </div>

    <div class="margin-top-20">
        @Html.ActionLink("Back to List", "Index", "Application")
    </div>

    <!-- Modals -->
    <!-- New User -->
    <div class="modal fade" id="ModalNewUser" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">

                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">Add User</h4>
                </div>

                <div class="modal-body" id="modalBodyAddUser">
                    @{Html.RenderAction("_RegisterUserPartial", "Account");}
                </div>

                <div class="modal-footer">
                    <!--Modal Add User Footer-->
                </div>

            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

    <!-- New Company -->
    <div class="modal fade" id="ModalNewCompany" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">

                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">Add User</h4>
                </div>

                <div class="modal-body" id="modalBodyAddCompany">
                    @{Html.RenderAction("_RegisterCompanyPartial", "Application");}
                </div>

                <div class="modal-footer">
                    <!--Modal Add User Footer-->
                </div>

            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

    <!-- Scripts -->
    <script>  
        $(document).ready(function () {

            //Open New User Modal
            $("#ButtonNewUser").click(function () {
                alert("1");
                $("#ModalNewUser").modal({ show: true, backdrop: false });
            });

            //Clear New User Modal
            $(".modal").on("hidden.bs.modal", function () {
                alert("2");
                $(this).find("#formNewUser")[0].reset();
            });

            //Open New Company Modal
            $("#ButtonNewCompany").click(function () {
                $("#ModalNewCompany").modal({ backdrop: false });
            });

        })
    </script>

部分视图:

@model CBA.Models.Account.RegisterUserViewModel

@{
    ViewBag.Title = "PartialRegisterUser";
    Layout = "~/Views/Shared/_LayoutModal.cshtml";
}



@ViewBag.Message

@using (Ajax.BeginForm("_RegisterUserPartial", "Account", new AjaxOptions
                                                                            {
                                                                                LoadingElementId = "formNewUser",
                                                                                HttpMethod = "Post",
                                                                                UpdateTargetId = "modalBodyAddUser",
                                                                                InsertionMode = InsertionMode.Replace,
                                                                            }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal" id="formNewUser">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-4" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-4" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-4" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-4" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @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" } })
                @Html.ValidationMessageFor(model => model.CompanyName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.RoleName, htmlAttributes: new { @class = "control-label col-md-4" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.RoleName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.RoleName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-4" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-4" })
            <div class="col-md-8">
                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-4 col-md-8">
                <input type="submit" value="Create" class="btn btn-default" />
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>

    <input type="button" value="reset" id="buttonResetForm"/>
}

控制器:

// GET: /Account/Register
        [AllowAnonymous]
        public async Task<PartialViewResult> _RegisterUserPartial()
        {
            ViewBag.Message = "Partial Register new user AccountController";
            //ModelState.Clear();
            var model = new RegisterUserViewModel() { CompanyName = "test1", Email = "test@2.se" };

            return PartialView(model);
        }

        //
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<PartialViewResult> _RegisterUserPartial(RegisterUserViewModel model)
        {
            //ModelState.Clear();
            //return View(model);
            return PartialView(model);
        }

布局:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>

    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>

<body>
    <div class="container body-content">
        @RenderBody()
    </div>

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

我已经插入一个警告(“某个数字”)以确认Jquery操作已被触发,它是。但“重置”部分没有。并且我尝试过哪个功能并不重要。似乎什么都没有做到......

我试过了,它清除字段但不清除验证消息。

参考文献:

// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js",
                        "~/Scripts/jquery.unobtrusive-ajax.js",
                        "~/Scripts/jquery-ui-1.11.4.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/caiugo.css",
                      "~/Content/bootstrap.css",
                      "~/Content/site.css")); 

1 个答案:

答案 0 :(得分:0)

在此片段之前:

$(".modal").on("hidden.bs.modal", function () {
    alert("2");
     $(this).find("#formNewUser")[0].reset();
 });

包括(或在一个不同的文件中):

&#13;
&#13;
(function ($) {
 
    //re-set all client validation given a jQuery selected form or child
    $.fn.resetValidation = function () {
 
        var $form = this.closest('form');
 
        //reset jQuery Validate's internals
        $form.validate().resetForm();
 
        //reset unobtrusive validation summary, if it exists
        $form.find("[data-valmsg-summary=true]")
            .removeClass("validation-summary-errors")
            .addClass("validation-summary-valid")
            .find("ul").empty();
 
        //reset unobtrusive field level, if it exists
        $form.find("[data-valmsg-replace]")
            .removeClass("field-validation-error")
            .addClass("field-validation-valid")
            .empty();
 
        return $form;
    };
 
    //reset a form given a jQuery selected form or a child
    //by default validation is also reset
    $.fn.formReset = function (resetValidation) {
        var $form = this.closest('form');
 
        $form[0].reset();
 
        if (resetValidation == undefined || resetValidation) {
            $form.resetValidation();
        }
 
        return $form;
    }
})(jQuery);
&#13;
&#13;
&#13;

所以,你最终会得到:

$(".modal").on("hidden.bs.modal", function () {
     alert("2");
     var theForm = $(this).find("#formNewUser");
      theForm[0].reset();
      theForm.resetValidation();
 });

您可以找到有关this plugin here的更多信息。