【问题标题】:How open Popup dialog windows and save data .net core mvc via ajax如何打开弹出对话框窗口并通过 ajax 保存数据 .net core mvc
【发布时间】:2020-06-21 13:20:29
【问题描述】:

我是 .NET 的新手,我想打开一个模式弹出窗口,然后将此数据保存到 db 而不重新加载页面。

首先,用户需要点击一个按钮。模态是通过 ajax 加载的。用户填写表单,然后验证内容并将其发布到数据库。

这是按钮的代码:

<button class="btn btn-primary" asp-controller="Positions" asp-action="Create" 
        data-toggle="ajax-modal" data-target="#add-contact">Add new Positions</button>

这是控制器:

// GET: Positions/Create
public IActionResult Create()
{
    return View();
}

// POST: Positions/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("PositionId,PositionName")] Position position)
{
    if (ModelState.IsValid)
    {
        _context.Add(position);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(position);
}

这是模型(很简单)

public class Position
{
    [Key]
    public int PositionId { get; set; }
    public string PositionName { get; set; }
}

这是我观点的代码:

@model Models.Position

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

<h3>Create Position</h3>
<hr/>
<div class="modal fade" id="add-contact" tabindex="-1" role="dialog" aria-labelledby="addPositionsLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addPositionsLabel">Add positions</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form asp-action="Create">
                    <input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" />
                    <div class="form-group">
                        <label asp-for="PositionName"></label>
                        <input asp-for="PositionName" class="form-control" />
                        <span asp-validation-for="PositionName" class="text-danger"></span>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" data-save="modal">Save</button>
            </div>
        </div>
    </div>
</div>


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

如何正确打开此弹出对话框窗口,然后将填充的行保存到 db(通过 ajax)而不重新加载页面?

【问题讨论】:

    标签: javascript jquery .net ajax asp.net-core


    【解决方案1】:

    为防止向db添加数据时页面引用,您需要使用ajax显示模态并将数据传递给Create方法。

    而且你还需要把需要刷新的数据内容(一部分,不是整个页面)放到partial view,保证页面不会刷新,并且可以看到最新的数据添加到页面.

    Index.cshtml:

    @model IEnumerable<Models.Position>
    
    @{
        ViewData["Title"] = "Index";
    }
    @section Scripts{
    
        <script type="text/javascript">
            $("#addBtn").click(function () {
                $.ajax({
                    url: $(this).attr("formaction"),
                }).done(function (msg) {
                    $("#AddContent").html(msg);
                    $("#add-contact").modal("show");
                })
            });
            $("body").on("click", "#save", function () {
                var form = $('form');
                var token = $('input[name="__RequestVerificationToken"]', form).val();
                $.ajax({
                    type: "post",
                    url: form.attr('action'),
                    data: {
                        __RequestVerificationToken: token,
                        position: {
                            PositionName: $("#PositionName").val()
                        }
                    },
                    dataType: "html",
                    success: function (result) {
                        $("#add-contact").modal("hide");
                        $("#partial").html(result);
                    }
                });
                return false;
            });
        </script>
    
    }
    
    <button class="btn btn-primary" asp-controller="Positions" asp-action="Create"
            data-toggle="ajax-modal" data-target="#add-contact" id="addBtn">
        Add new Positions
    </button>
    <br />
    <div class="modal fade" id="add-contact" tabindex="-1" role="dialog" aria-labelledby="addPositionsLabel" aria-hidden="true">
        <div id="AddContent">
        </div>
    </div>
    <div id="partial">
        @Html.Partial("_PositionList", Model)
    </div>

    创建.cshtml:

    @model Models.Position
    
    @{
        ViewData["Title"] = "Create";
        Layout = null;
    }
    
    <h3>Create Position</h3>
    <hr />
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addPositionsLabel">Add positions</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form asp-action="Create">
                    <input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" />
                    <div class="form-group">
                        <label asp-for="PositionName"></label>
                        <input asp-for="PositionName" class="form-control" />
                        <span asp-validation-for="PositionName" class="text-danger"></span>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" data-save="modal" id="save">Save</button>
            </div>
        </div>
    </div> 

    _PositionList.cshtml(部分视图):

    @model IEnumerable<Models.Position>
    <table class="table-bordered">
        <tr>
            <th>
                PositionId
            </th>
            <th>
                PositionName
            </th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.PositionId
                </td>
                <td>
                    @item.PositionName
                </td>
    
            </tr>
        }
    </table>

    PositionsController.cs:

    public IActionResult Index()
        {
            return View( _context.Position.ToList());
        }
        public IActionResult Create()
        {
            return View();
        }
    
        // POST: Positions/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("PositionId,PositionName")] Position position)
        {
            if (ModelState.IsValid)
            {
                _context.Add(position);
                await _context.SaveChangesAsync();
                return  PartialView("_PositionList", _context.Position.ToList());
            }
            return View(position);
        }
    

    结果如下:

    【讨论】:

    • 然后我把 Layout = null;到 Create.cshtml VS 显示错误 i.imgur.com/TXyGm8t.pngurl: $(this).attr("formaction")? 是什么你能把项目放在 github 或 google 驱动器上吗?
    • 在控制台中我看到 Uncaught TypeError: $.ajax is not a function i.imgur.com/lUSq73s.png
    • @cickness 你可以删除 Create.cshtml 中的 '@section Scripts' 和 'url: $(this).attr("formaction")? ' 是按钮的 'asp-controller' 和 'asp-action',我将按钮的 id 设置为 'addBtn'。
    • 第二条评论(错误),请确保Index.cshtml使用的是常规(压缩或非压缩)版本的jQuery(不是jQuery的slim build),你可以参考这个:stackoverflow.com/a/40712438/12884742
    • @cickness 我已经把我的demo上传到了github,这里是链接:github.com/YongqingYu-qq/.net-core-create-data
    猜你喜欢
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 2010-11-24
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    相关资源
    最近更新 更多