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">×</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?