I am following this guide (https://softdevpractice.com/blog/asp-net-core-mvc-ajax-modals/), and cannot get the save button on my modal to work. I tried putting it within the form tag but then it was using the form action from the parent view not the partial.
At first I could not get the close buttons to work but that was resolved by changing data-dismiss to data-bs-dismiss. I am wondering if I need to do similarly for save, since things have changed with Bootstrap 5.
My code is as follows:
Parent View
<div id="AddStudyModal"></div>
// Irrelevant stuff here
<div>
<button type="button" data-toggle="ajax-modal" data-bs-target="#add-study" data-url="@Url.Action("AddStudy", "App", new {id = Model.GUID})">Add</button>
</div>
Partial View
<div id="add-study" tabindex="-1" role="dialog" aria-labelledby="addStudyLabel" aria-hidden="true">
<div role="document">
<div >
<div >
<h5 id="addStudyLabel">Add Study</h5>
<button type="button" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div >
<form asp-controller="App" asp-action="AddParticipant" method="post">
@Html.HiddenFor(m => m.ParticipantGuid)
<div asp-validation-summary="ModelOnly"></div>
<div >
<label asp-for="Studies" ></label>
<select asp-for="SelectedStudyGuid" asp-items="Model.Studies" autocomplete="off">
<option value=""> Select a Study</option>
</select>
<span asp-validation-for="SelectedStudyGuid" ></span>
</div>
<div >
<label asp-for="StartDate" ></label>
<input asp-for="StartDate" autocomplete="off"/>
<span asp-validation-for="StartDate" ></span>
</div>
<div >
<label asp-for="EndDate" ></label>
<input asp-for="EndDate" autocomplete="off"/>
<span asp-validation-for="EndDate" ></span>
</div>
<div >
</div>
<div >@ViewBag.Message</div>
</form>
</div>
<div >
<button type="button" data-bs-dismiss="modal">Close</button>
<button type="button" data-save="modal">Save</button>
</div>
</div>
</div>
</div>
site.js
$(function (){
var AddStudyElement = $('#AddStudyModal');
$('button[data-toggle="ajax-modal"]').click(function(event){
var url = $(this).data('url');
$.get(url).done(function(data){
AddStudyElement.html(data);
AddStudyElement.find('.modal').modal('show');
})
})
AddStudyElement.on('click', '[data-save="modal"]', function(event){
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function(data){
AddStudyElement.find('modal').modal('hide');
})
})
})
Edit: I got the Save button to do something now (close the Modal) thanks to @Efraim's help with adding the . in front of modal.
CodePudding user response:
there is a missing '.' in: AddStudyElement.find('modal').modal('hide'); AddStudyElement.find('.modal').modal('hide');
