弹出窗口不以错误的形式返回值

时间:2019-01-28 08:26:14

标签: javascript c# ajax model-view-controller modal-dialog

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

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

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

回发之前和之后:

enter image description here

弹出窗口视图:

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

1 个答案:

答案 0 :(得分:0)

由于我没有添加布局,因此页面上缺少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() );