I have a table that has dynamic buttons which bring up a modal with info. Within the modal i want to add a new row to a table when i click a button.
I display the modal from within my main view, then call a partial to show the info inside the table in the modal.
From within the partial I've tried using append but doesn't seem to work, I thought jQuery could add to the table and I wouldn't have to invoke any kind of refresh.
My question is: how can I refresh my table from inside the partial?
I believe that jQuery is adding to the td but its just not being updated
EditApplication.cshmtl main view
<form method="POST">
<div class="modal fade" id="editAppModal" tabindex="-1" role="dialog" aria-labelledby="editAppModal" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editAppModal">Edit Application</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<input type="text" id="appName">
<input type="text" id="appShortName" style="width:15%">
<hr>
<table id="modalServerTB" style="border-collapse: separate; border-spacing: 5px 15px;">
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" asp-page-handler="UpdateApplication">Update Application</button>
</div>
</div>
</div>
</div>
</form>
jQuery in main view
<script>
$(document).ready(function(){
$(".selectRow").click(function(e)
{
e.preventDefault();
var row = $(this).closest("tr"),
tds = row.find("td:nth-child(1)").first(); //get row closest to click then grab first column info
var textval = $.trim(tds.text()); //tons of whitespace around the text, needs to be removed
$.ajax({
url: "EditApplication?handler=GetRowInfo",
type: "POST",
dataType: "json",
data: { textval },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
complete: function (result) {
$("#appName").val(textval);
$("#appShortName").val(result.responseJSON);
$('#modalServerTB').load('/EditApplication?handler=ServerPartial');
$('#editAppModal').modal('show');
}
})
});
});
</script>
partial view
<tbody id="tableBody">
#foreach(var s in Model.serverUrl)
{
<tr style="border-bottom: 0.3px outset whitesmoke" >
<td style="width:40%">
<input type="text" value="#s.Key">
</td>
<td>
#foreach(var u in s.Value)
{
#Html.DropDownListFor(a=>u.Urlid, Model.urls, new{style = "width:50%", #class = "selectedURL"})
<br>
}
</td>
<td class="newURLS" style="border:solid 1px">
</td>
<button class="AddURLBtn"> + </button>
<br>
</tr>
}
</tbody>
<div>
<button type="button" class="btn btn-dark btn-sm" id="AddServerBtn">Add Server </button>
</div>
#Html.DropDownList("selectedURL",Model.urls, "Select URL" , new {style = "width:50%; display:none;", #class = "selectedURL", id="urlDDL"})
<script>
$(document).ready(function(){
$(".AddURLBtn").click(function(e)
{
e.preventDefault();
console.log("inaddurl");
$(".newURLS").append('sgagfsafsafsf');
});
});
</script>
As of right now i was just testing to see if i can add just text to the td but it doesn't seem to work
I am also passing a view model to my partial
Turns out you need a table tag for this to all work. With just TBody the div was not being created therefore my jquery function had no target
<table>
<tbody id="tableBody">
#foreach(var s in Model.serverUrl)
{
<tr style="border-bottom: 0.3px outset whitesmoke" >
<td style="width:40%">
<input type="text" value="#s.Key">
</td>
<td class="urlsTD">
#foreach(var u in s.Value)
{
#Html.DropDownListFor(a=>u.Urlid, Model.urls, new{style = "width:50%", #class = "selectedURL"})
<br>
}
</td>
<td>
<button class="AddURLBtn"> + </button>
</td>
</tr>
}
</tbody>
<div>
<button type="button" class="btn btn-dark btn-sm" id="AddServerBtn">Add Server </button>
</div>
</table>
Related
I hava a list of objects in my view. In a table, with some conditions I create rows and add a button. I want to pass that row's data to my controller when button of modal-footer is pressed. I tried ajax request and forms but I could not manage that up. What is coming to my controller is always the first element of list.
My view:
<table class="table border-bottom dataTable" id="dataTable" width="100%" cellspacing="0" role="grid" aria-describedby="dataTable_info" style="width: 100%;">
<thead>
<tr><th rowspan="1">Saat</th><th rowspan="1">Durum</th></tr>
</thead>
#{int i = 0; }
#foreach (var v in Model)
{
<tbody>
<tr>
#if (v.IsActive == 1)
{
<td>#v.Hour.ToString():#v.Minute.ToString().ElementAt(0)0</td>
<td><p class="blckpassive">Dolu</p></td>
}
else
{
<td>#v.Hour.ToString():#v.Minute.ToString().ElementAt(0)0</td>
<td><p class="blckactive">Boş</p></td>
<td><button type="button" class="btn btn-info" data-toggle="modal" data-target="#exampleModal">Randevu Al</button></td>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Emin Misiniz?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Seçtiğiniz Randevuyu Almak İstiyor Musunuz?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">İptal</button>
<a type="button" href="/Appointment/AddAppointment?hour=#v.Hour" class="btn btn-primary">Evet</a>
</div>
</div>
</div>
</div>
}
</tr>
</tbody>
i++;
}
</table>
Controller:
public IActionResult AddAppointment(int hour)
{
return null;
}
Objects in list has hour and minute variables which are int and sorted as "9:00,9:30,10:00,10:30...16:00".
What is coming to my controller is always the first element of list.
You put the code of popup modal dialog in a foreach loop, if you check the html source code, you can find that multiple button(s) with same value #exampleModal of data-target attribute, and target modal(s) with same value exampleModal of id attribute, which cause the above issue.
To resolve this issue and make modal popup works well, you can modify the code as below to make the data-target attribute of button trigger and id attribute of modal unique within the HTML document.
<td><button type="button" class="btn btn-info" data-toggle="modal" data-target=#("#exampleModal"+i)>Randevu Al</button></td>
<div class="modal fade" id=#("exampleModal"+i) tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
Test Result
I am trying, trying and trying but I don't come to a solution.. :(
It would be great if someone experienced could have a look into it.
My situation:
I have a table with multiple rows and one row with button(s). One if those are a "Cancel" button to delete the data record. In generel this is working perfectly but I implemented a modal dialog to ask the user before processing the cancel if he's really sure to cancel it.
Since I implemented the modal dialog, on the button click the selected row always changes to the first row and not the row where the user clicked on. So if the user clicks on the "Cancel" button in row 2, it shows the data of row 1 in the modal popup and also redirects the ID of row 1 to the controller.
My View:
#model ViewModels.ServicesViewModel
<table class="table table-hover">
<tr>
<th>DB Name</th>
<th>DB Description</th>
<th>DB Version</th>
<th>Access valid until</th>
<th>Action</th>
</tr>
#foreach (var item in Model.AssignedDatabases)
{
<tr>
<td style="width:20%">#item.DB_Name</td>
<td style="width:35%">#item.DB_Description</td>
<td style="width:10%">#item.DB_Version</td>
<td style="width:15%">#item.ExpiryDate</td>
<td style="width:20%">
#if (item.RequestState.Equals("Open"))
{
<i class="btn btn-info btn-md" style="font-family:Arial">Pending</i>
}
else
{
<i data-toggle="modal" data-target="#exampleModal" class="btn btn-danger btn-md" style="font-family:Arial">Cancel</i>
}
#if (Model.ResponsibleDBs.Exists(x => x.DB_UID == item.DB_UID))
{
<i class="btn btn-success btn-md" style="font-family:Arial">Manage</i>
}
#using (Html.BeginForm("Delete", "AssignedDatabases", FormMethod.Post))
{
<div id="exampleModal" class="modal" tabindex="3" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Do you really want to cancel the access to #item.DB_Name ?</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<i class="btn btn-success btn-md" style="font-family:Arial">Yes</i>
<i data-dismiss="modal" class="btn btn-danger btn-md" style="font-family: Arial">No</i>
</div>
</div>
</div>
</div>
}
</td>
</tr>
}
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<i class="btn btn-success btn-md" style="font-family:Arial">Request new</i>
</td>
</tr>
</table>
<script type="text/javascript">
$(function () {
$('body').on('click', 'a.modal-link', function (e) {
e.preventDefault();
$("#modal").remove();
// Get the Details action URL
var url = $(this).attr("href");
//Make the Ajax call and render modal when response is available
$.get(url, function (data) {
$(data).modal();
});
});
});
</script>
Does anyone have an idea what I'm doing wrong? Thank you!
BR,
Phil
Your issue comes from the usage of the non-unique ID #exampleModal. Thus the browser always uses the first element with that ID.
If you want to leave the modal within the foreach loop, you should append something unique to the ID.
#Niyak
You are the king! Thank you!
I added a unique identifier to the datatarget and modal and now its working.
So simple... Sometimes you can't see the forest for the trees :)
Changed the code now to:
#model ViewModels.ServicesViewModel
<table class="table table-hover">
<tr>
<th>DB Name</th>
<th>DB Description</th>
<th>DB Version</th>
<th>Access valid until</th>
<th>Action</th>
</tr>
#foreach (var item in Model.AssignedDatabases)
{
var dataTargetCancel = "#ModalCancel" + item.DB_UID;
var modalID = "ModalCancel" + item.DB_UID;
<tr>
<td style="width:20%">#item.DB_Name</td>
<td style="width:35%">#item.DB_Description</td>
<td style="width:10%">#item.DB_Version</td>
<td style="width:15%">#item.ExpiryDate</td>
<td style="width:20%">
#if (item.RequestState.Equals("Open"))
{
<i class="btn btn-info btn-md" style="font-family:Arial">Pending</i>
}
else
{
<i data-toggle="modal" data-target="#dataTargetCancel" class="btn btn-danger btn-md" style="font-family:Arial">Cancel</i>
}
#if (Model.ResponsibleDBs.Exists(x => x.DB_UID == item.DB_UID))
{
<i class="btn btn-success btn-md" style="font-family:Arial">Manage</i>
}
#using (Html.BeginForm("Delete", "AssignedDatabases", FormMethod.Post))
{
<div id="#modalID" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Do you really want to cancel the access to #item.DB_Name ?</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<i class="btn btn-success btn-md" style="font-family:Arial">Yes</i>
<i data-dismiss="modal" class="btn btn-danger btn-md" style="font-family: Arial">No</i>
</div>
</div>
</div>
</div>
}
</td>
</tr>
}
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<i class="btn btn-success btn-md" style="font-family:Arial">Request new</i>
</td>
</tr>
</table>
<script type="text/javascript">
$(function () {
$('body').on('click', 'a.modal-link', function (e) {
e.preventDefault();
$("#modal").remove();
// Get the Details action URL
var url = $(this).attr("href");
//Make the Ajax call and render modal when response is available
$.get(url, function (data) {
$(data).modal();
});
});
});
</script>
I have a form that displays a persons title and name.It shows a lot more than that, but this is the bit I am asking about.
I have a person table.
If the user wants to change the person details, is it possible to open up a pop up modal form that lists all the persons in the person table, so that the user can either select an existing person, or insert a new person and when the user closes the pop up, the main form is populated with the selected/new persons details?
I am using ASP.NET Core MVC 5 and EF Core 5.
Any help or pointing to a tutorial would be a great help, thanks.
UPDATE -
I have tried the following -
I have created a modal partial view -
#model Person
<div class="modal fade" id="personModal" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="personModalLabel">Persons</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Create">
<table class="table table-bordered table-striped table-hover">
<tbody>
#foreach (var pers in ViewBag.PersonList)
{
<tr>
<td style="display:none">#pers.Id</td>
<td class="text-left">
<a asp-action="details" asp-controller="admin" asp-route-id="#pers.Id" title="Click to select vaccination centre">#pers.Title.Description</a><br />
</td>
<td class="text-left ">
#pers.Forename
</td>
<td class="text-left ">
#pers.Surname
</td>
</tr>
}
</tbody>
</table>
<br />
<div class="form-row">
<label asp-for="TitleId" class="control-label col-md-2">Title</label>
<div class="col-md-4 mb-2">
<select asp-for="TitleId" asp-items="#(new SelectList(ViewBag.TitleList, "Id", "Description"))" style=" width: 363px; height: 37px"></select>
<span asp-validation-for="TitleId" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<label asp-for="Forename" class="control-label col-md-2">Forename</label>
<div class="col-md-4 mb-2">
<input asp-for="Forename" class="form-control" maxlength="100" />
<span asp-validation-for="Forename" class="text-danger"></span>
</div>
</div>
<div class="form-row">
<label asp-for="Surname" class="control-label col-md-2">Surname</label>
<div class="col-md-4 mb-2">
<input asp-for="Surname" class="form-control" maxlength="100" />
<span asp-validation-for="Forename" class="text-danger"></span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save</button>
</div>
</div>
</div>
</div>
I have added the following script to site.js -
$(function () {
var placeHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function(data) {
placeHolderElement.html(data);
placeHolderElement.find('.modal').modal('show');
})
})
placeHolderElement.on('Click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
placeHolderElement.find('.modal').modal('hide');
})
})
})
And the controller -
[HttpGet]
public IActionResult Create()
{
List<Person> personList = _personRepository.Persons.ToList();
ViewBag.PersonList = personList;
List<Title> titleList = _titleRepository.Titles.ToList();
ViewBag.TitleList = titleList;
Person pers = new Person();
return PartialView("_PersonModalPartial", pers);
}
[HttpPost]
public IActionResult Create(Person pers)
{
_personRepository.CreatePerson(pers);
List<Person> personList = _personRepository.Persons.ToList();
ViewBag.PersonList = personList;
List<Title> titleList = _titleRepository.Titles.ToList();
ViewBag.TitleList = titleList;
return PartialView("_PersonModalPartial", pers);
}
I call the modal with the the following in my main form -
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create")" >Insert</button>
The above code shows the modal and populates the table.
However nothing happens when you press save!?
UPDATE 2 -
I changed the button in the modal for to
input type="submit" value="Submit" name="Submit" class="btn btn-success float-right" id="SubmitForm" />
And then changed the form tag in my modal form to -
<form method="post" asp-controller="Admin" asp-action="Create">
That worked.
Now I am wondering how you can pass the id value of the model into the Modal form using the data-url part of the calling button?
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create")" >Insert</button>
You can use #Url.Action("Create",new { id=xxx}),here is a demo:
Html(I use "sss" as a sample data of id):
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create1",new { id="sss"})">
Insert
</button>
js:
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeHolderElement.html(data);
placeHolderElement.find('.modal').modal('show');
})
})
Controller:
public IActionResult Create1(string id) {
return Ok();
}
result:
Update:
If you want to use #Model.Id:
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#personModal"
data-url="#Url.Action("Create1",new { id=Model.Id})">
Insert
</button>
i am trying to populate modals with different data, i create the modals buttons using a foreach loop and then i want to apply the relevant data to the right modal.
The problem i have is that the modal is showing the same data for each modal button. How can i make this unique? When its doing its loop its actually placing the correct info but when the page loads its only showing one type of data for every modal.
#foreach (DataRow row in Model.Tables[0].Rows)
{
<tr>
<td>#row["SerialNumber"]</td>
<td>#row["DtTmGenerated"]</td>
<td>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal">View Error</button>
</td>
</tr>
}
</thead>
<tbody></tbody>
</table>
#if (Model.Tables[0].Rows.Count != 0)
{
<script type='text/javascript'>
window.onload = function() {
document.getElementById("cssClass").style.display = 'none';
}
</script>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title justify-content-center">Panda Error information</h4>
</div>
<div class="modal-body">
#foreach (DataRow row in Model.Tables[0].Rows)
{
var test = Convert.ToString(row["FriendlyError"]);
if (test != "No Error" )
{
<p>#row["FriendlyError"]</p>
}
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
I'm a bit late but I had the same problem today and I managed to fix it :D
The problem is the ID of the modal. In each new loop pass your modal is created with the same ID.
In other words: Your values, which come into the modal always change, but because the ID is static, all further modals get the same values as in the first one, because all have the same ID. Try this:
Add this code right after your model (#model ...)
#{
int ModalId = 0;
}
Then change the ID in the button that opens your modal:
data-target="##ModalId"
In the line before you close your foreach, add this
#(ModalId++)
Change your modal to this and put it into your foreach so that it looks like this:
#foreach (DataRow row in Model.Tables[0].Rows)
{
<tr>
<td>#row["SerialNumber"]</td>
<td>#row["DtTmGenerated"]</td>
<td>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="##ModalId">View Error</button>
<!-- Modal -->
<div id="#ModalId" aria-labelledby="#ModalId" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title justify-content-center">Panda Error information</h4>
</div>
<div class="modal-body">
#foreach (DataRow row in Model.Tables[0].Rows)
{
var test = Convert.ToString(row["FriendlyError"]);
if (test != "No Error")
{
<p>#row["FriendlyError"]</p>
}
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</td>
</tr>
#(ModalId++)
}
</thead>
<tbody>
</tbody></table>
#if (Model.Tables[0].Rows.Count != 0)
{
<script type='text/javascript'>
window.onload = function() {
document.getElementById("cssClass").style.display = 'none';
}
</script>
}
</body>
</html>
In summary: Wherever you had "myModal" as ID, you must replace it with #ModalId
I have a textbox that when the user enters a string and presses a button this is then compared to find which matching fields are in database. I also have another button that launches the display of a bootstrap modal which then views the results.
The issue I'm having is I only want one button but when I try to combine the two i get the modal and the string search never happens.
Can anyone tell me how I combine the two ?
Button 1 (search string button)
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
<label for="platform" class="control-label">Enter Code:</label><br />
#Html.TextBox("filtername")
<input type="submit" value="Filter" "/>
</p>
}
Button 2 (Activates modal but no data comparision)
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10">
<div class="span7 text-center">
<input type="text" class="form-control" id="theCode" placeholder="Please Enter Code">
<input type="submit" value="Go!" class="btn btn-success" id="sendcoderequest" data-toggle="modal"
data-target="#basicModal2" />
</div>
</div>
</div>
Home/Index Method:
public ActionResult Index(string filtername)
{
var filterresults = from m in db.UserInfoes
select m;
filterresults = filterresults.Where(x => x.UserCode.ToString().Contains(filtername)).OrderBy(x => x.UserCode);
return View(filterresults);
}
Modal :
<div class="modal fade" id="basicModal2" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Summary</h4>
</div>
<div class="modal-body">
<h2>Results</h2>
<span id="printCode"></span><br />
<div class="pull-right"><button type="submit" class="btn btn-success" id="toggle">Toggle</button> </div>
<table class="table">
<thead>
<tr>
<th></th>
<th>Date</th>
<th>Test Type</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" class="checks">
</td>
<td>
#Html.DisplayFor(modelItem => item.CreationDateTime)
</td>
<td>
#Html.DisplayFor(modelItem => item.AppModeId)
</td>
</tr>
}
</tbody>
</table>
Code currently working with:
Form:
<form id="formid">
<label for="platform" class="control-label">Enter Code:</label>
<input type="text" name="filtername" />
<input type="submit" class="btn btn-success" value="Filter" />
</form>
JQuery:
$("#formid").submit(function () {
$.ajax({
url: "Home",
data: $(this).serialize()
}).done(function (response) {
$('#modal_content').html(response);
$('#basicModal2').modal('show');
});
return false; // prevent the form submission
});
Modal is unchanged.
You could use an AJAX call instead of the form submission. Then you could open the modal via Javascript once you receive the AJAX response. According to the tags, you're probably using JQuery, so it would look like this :
$("form").submit(function(){
$.ajax({
url: "Home",
data: $(this).serialize()
}).done(function(response){
// Fill your modal window with the response here
$('#basicModal2').modal('show');
});
return false; // prevent the form submission
});
Edit
You can find here an example that uses AJAX to send the filter name to the server, fill the modal with the server response and finally show the modal:
http://jsfiddle.net/yohanrobert/e3p4yv55/