admin管理员组

文章数量:1323689

I am new in .NET and I want to open a modal popup and then save this data to db without reloading the page.

First of all, the user needs to click on a button. Modal is loaded via ajax. The user fills the form, then the content is validated and is posted to the database.

This is the code of the button:

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

This is the controller:

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

This is the model (very simple)

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

This is the code of my view:

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

How can I properly open this popup dialog window and then save the filled rows to db(via ajax) without the page reloading?

I am new in .NET and I want to open a modal popup and then save this data to db without reloading the page.

First of all, the user needs to click on a button. Modal is loaded via ajax. The user fills the form, then the content is validated and is posted to the database.

This is the code of the button:

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

This is the controller:

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

This is the model (very simple)

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

This is the code of my view:

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

How can I properly open this popup dialog window and then save the filled rows to db(via ajax) without the page reloading?

Share edited Mar 9, 2020 at 17:28 cickness asked Mar 9, 2020 at 15:54 cickness cickness 9172 gold badges7 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

To prevent page refersh when add data to db, you need to use ajax to display the modal and pass data to the Create method.

And you also need to put the data content that you need to refresh(a part, not the entire page) to the partial view to ensure that the page will not refresh and you can see the newest data added to the page.

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>

Create.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(partial view):

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

Here is the result :

本文标签: javascriptHow open Popup dialog windows and save data net core mvc via ajaxStack Overflow