弹出窗口不以错误的形式返回值 [英] Popup not returning values in form with errors

查看:56
本文介绍了弹出窗口不以错误的形式返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Core 2.1,C#,MVC. 我有一个模式弹出窗口,当我使用ajax提交表单时,在同一弹出窗口上未显示模型错误(必填字段等)时,它只显示了模态,如下面的照片,没有任何更改.

我做错了什么?如果在邮包打包后未完成,如何显示必填字段?

我认为问题在于模式弹出窗口没有刷新.

回发之前和回发之后:

弹出窗口视图:

@model CharityProject.Models.UserInfos

@{
    ViewData["Title"] = "Create";

    Layout = "";
}

<h2>Create</h2>

<h4>UserInfos</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="CreateAddress" id="createform">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            @if (User.IsInRole("Admin"))
            {
                <div class="form-group">
                    <label asp-for="ApplicationUserId" class="control-label"></label>
                    <select asp-for="ApplicationUserId" class="form-control" asp-items="ViewBag.ApplicationUserId"></select>
                </div>
            }

            <div class="form-group">
                <label asp-for="CitiesId" class="control-label"></label>
                <select asp-for="CitiesId" class="form-control" asp-items="ViewBag.CitiesId"></select>
            </div>
            <div class="form-group">
                <label asp-for="Area" class="control-label"></label>
                <input asp-for="Area" class="form-control" />
                <span asp-validation-for="Area" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address" class="control-label"></label>
                <input asp-for="Address" class="form-control" />
                <span asp-validation-for="Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="POB" class="control-label"></label>
                <input asp-for="POB" class="form-control" />
                <span asp-validation-for="POB" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PhoneNo" class="control-label"></label>
                <input asp-for="PhoneNo" class="form-control" />
                <span asp-validation-for="PhoneNo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PhoneNo2" class="control-label"></label>
                <input asp-for="PhoneNo2" class="form-control" />
                <span asp-validation-for="PhoneNo2" class="text-danger"></span>
            </div>
            <div class="form-group">
                <div class="checkbox">
                    <label>
                        <input asp-for="IsDefault" /> @Html.DisplayNameFor(model => model.IsDefault)
                    </label>
                </div>
            </div>
            <div class="form-group">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <input type="submit" class="btn btn-primary" value="Save" />
            </div>

        </form>
    </div>
</div>
<environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

    <script>
    jQuery(document).ready(function ($) {
        $("#createform").submit(function (e) {
            debugger;
            e.preventDefault();

            console.log('Doing ajax submit');

            var formAction = $(this).attr("action");



            $.ajax({
                type: "POST",
                url: formAction,
                async: true,
                data: $('#createform').serialize() ,
                dataType: "json",
                success: function (content) {
                    debugger;
                    $('#myModal').find("div.modal-body").html(content);
                    // $('#myModal').modal("hide");
                },
                error: function (e) {
                    debugger;
                    var msg = e;
                }
            });

        });
    })
    </script>

父视图:

@model IEnumerable<CharityProject.Models.UserInfos>

@{
    ViewData["Title"] = "SelectAddress";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Select Address</h2>

<p>
    @* <input type="button" value="Add New Address" onclick="location.href='@Url.Action("Create", "UserInfos")'" />*@
    <input type="button" data-toggle="modal" data-target="#myModal" value="Add New Address" class="btn btn-default" id="showthis">
</p>
<div class="row">
    <div class="col-md-6">
        <table class="table">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Cities)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Area)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Address)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.POB)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.PhoneNo)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.PhoneNo2)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.IsDefault)
                    </th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.Cities.CityName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Area)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Address)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.POB)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.PhoneNo)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.PhoneNo2)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.IsDefault)
                        </td>
                        <td>
                            <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                            <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                            <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
    <div class="col-md-6">


    </div>
</div>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close"  aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">

            </div>

        </div>
    </div>
</div>

<script>
    jQuery(document).ready(function ($) {

        $('#showthis').click(function (e) {


            debugger;
            $.ajax({
                type: "GET",
                url: 'CreateAddress',
                async: false,
                success: function (content) {
                    $('#myModal').find("div.modal-body").html(content);
                },
                error: function (e) { }
            });
        });

    })
</script>

控制器:

   [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CreateAddress([Bind("Id,CitiesId,Area,Address,POB,PhoneNo,PhoneNo2,IsDefault,ApplicationUserId")] UserInfos userInfos)
        {
            var userid = _userManager.GetUserId(User);
            if (!User.IsInRole("Admin"))
            {
                userInfos.ApplicationUserId = userid;
            }
            if (ModelState.IsValid)
            {
                _context.Add(userInfos);
                await _context.SaveChangesAsync();
                // return RedirectToAction(nameof(Index));
                return Json(new { status = "success" });
            }
            ViewData["CitiesId"] = new SelectList(_context.Cities, "Id", "CityName", userInfos.CitiesId);
            ViewData["ApplicationUserId"] = new SelectList(_context.Users.Include(u => u.UserRoles).ThenInclude(u => u.Role).Where(o => o.UserRoles.All(r => r.Role.Name == "Customer")), "Id", "Email", userInfos.ApplicationUserId);
           // return View(userInfos);
            return Json(new { content = userInfos });
        }

解决方案

我没有从页面上丢失2个JS引用文件,因为我没有添加布局.

<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>

此外,如果您想使用表格的模型,也可以使用

var data = JSON.stringify( $(form).serializeArray() );

I am using ASP.NET Core 2.1, C#, MVC. I have a modal popup and when I submit the form with ajax not showing the errors of the model (required fields etc) on the same popup window, it just shows the modal like the photo below without any changes.

What I am doing wrong and how i can show the required fields if not completed after post pack?

I think the problem is modal popup is not refreshing.

before post back and after post back:

Popup View:

@model CharityProject.Models.UserInfos

@{
    ViewData["Title"] = "Create";

    Layout = "";
}

<h2>Create</h2>

<h4>UserInfos</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="CreateAddress" id="createform">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            @if (User.IsInRole("Admin"))
            {
                <div class="form-group">
                    <label asp-for="ApplicationUserId" class="control-label"></label>
                    <select asp-for="ApplicationUserId" class="form-control" asp-items="ViewBag.ApplicationUserId"></select>
                </div>
            }

            <div class="form-group">
                <label asp-for="CitiesId" class="control-label"></label>
                <select asp-for="CitiesId" class="form-control" asp-items="ViewBag.CitiesId"></select>
            </div>
            <div class="form-group">
                <label asp-for="Area" class="control-label"></label>
                <input asp-for="Area" class="form-control" />
                <span asp-validation-for="Area" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address" class="control-label"></label>
                <input asp-for="Address" class="form-control" />
                <span asp-validation-for="Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="POB" class="control-label"></label>
                <input asp-for="POB" class="form-control" />
                <span asp-validation-for="POB" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PhoneNo" class="control-label"></label>
                <input asp-for="PhoneNo" class="form-control" />
                <span asp-validation-for="PhoneNo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PhoneNo2" class="control-label"></label>
                <input asp-for="PhoneNo2" class="form-control" />
                <span asp-validation-for="PhoneNo2" class="text-danger"></span>
            </div>
            <div class="form-group">
                <div class="checkbox">
                    <label>
                        <input asp-for="IsDefault" /> @Html.DisplayNameFor(model => model.IsDefault)
                    </label>
                </div>
            </div>
            <div class="form-group">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <input type="submit" class="btn btn-primary" value="Save" />
            </div>

        </form>
    </div>
</div>
<environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

    <script>
    jQuery(document).ready(function ($) {
        $("#createform").submit(function (e) {
            debugger;
            e.preventDefault();

            console.log('Doing ajax submit');

            var formAction = $(this).attr("action");



            $.ajax({
                type: "POST",
                url: formAction,
                async: true,
                data: $('#createform').serialize() ,
                dataType: "json",
                success: function (content) {
                    debugger;
                    $('#myModal').find("div.modal-body").html(content);
                    // $('#myModal').modal("hide");
                },
                error: function (e) {
                    debugger;
                    var msg = e;
                }
            });

        });
    })
    </script>

Parent View:

@model IEnumerable<CharityProject.Models.UserInfos>

@{
    ViewData["Title"] = "SelectAddress";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Select Address</h2>

<p>
    @* <input type="button" value="Add New Address" onclick="location.href='@Url.Action("Create", "UserInfos")'" />*@
    <input type="button" data-toggle="modal" data-target="#myModal" value="Add New Address" class="btn btn-default" id="showthis">
</p>
<div class="row">
    <div class="col-md-6">
        <table class="table">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Cities)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Area)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Address)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.POB)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.PhoneNo)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.PhoneNo2)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.IsDefault)
                    </th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.Cities.CityName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Area)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Address)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.POB)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.PhoneNo)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.PhoneNo2)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.IsDefault)
                        </td>
                        <td>
                            <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                            <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                            <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
    <div class="col-md-6">


    </div>
</div>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close"  aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">

            </div>

        </div>
    </div>
</div>

<script>
    jQuery(document).ready(function ($) {

        $('#showthis').click(function (e) {


            debugger;
            $.ajax({
                type: "GET",
                url: 'CreateAddress',
                async: false,
                success: function (content) {
                    $('#myModal').find("div.modal-body").html(content);
                },
                error: function (e) { }
            });
        });

    })
</script>

Controller:

   [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> CreateAddress([Bind("Id,CitiesId,Area,Address,POB,PhoneNo,PhoneNo2,IsDefault,ApplicationUserId")] UserInfos userInfos)
        {
            var userid = _userManager.GetUserId(User);
            if (!User.IsInRole("Admin"))
            {
                userInfos.ApplicationUserId = userid;
            }
            if (ModelState.IsValid)
            {
                _context.Add(userInfos);
                await _context.SaveChangesAsync();
                // return RedirectToAction(nameof(Index));
                return Json(new { status = "success" });
            }
            ViewData["CitiesId"] = new SelectList(_context.Cities, "Id", "CityName", userInfos.CitiesId);
            ViewData["ApplicationUserId"] = new SelectList(_context.Users.Include(u => u.UserRoles).ThenInclude(u => u.Role).Where(o => o.UserRoles.All(r => r.Role.Name == "Customer")), "Id", "Email", userInfos.ApplicationUserId);
           // return View(userInfos);
            return Json(new { content = userInfos });
        }

解决方案

I was missing 2 JS references files from the page because I didn't added layout.

<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>

Also if you want to take the Model of the form you can do it with

var data = JSON.stringify( $(form).serializeArray() );

这篇关于弹出窗口不以错误的形式返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆