Popup not returning values in form with errors

守給你的承諾、 提交于 2019-12-11 15:36:41

问题


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 });
        }

回答1:


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() );


来源:https://stackoverflow.com/questions/54397996/popup-not-returning-values-in-form-with-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!