Dynamic content for model popup based on link selected - javascript

I have an array of Accept Reject button. if a user clicks on these buttons separate model popup will show. Accept and reject button link has separate data-id and data-action.
My aim to write a single javascript function to load the content of the model popup instead of repeating the code of modal.
ERB code
<% #non_claim_items.each do |damage_item| %>
<tr>
<td>
<div class="input-prepend">
<span class="add-on"><%= damage_item.estimated_total_repair_cost.currency %></span>
<span class="uneditable-input input-small currency-format"><%= damage_item.estimated_total_repair_cost %></span>
</div>
</td>
<td>
<a data-toggle="modal" data-target="#acceptModel" data-id="<%= damage_item.id %>" data-action = 'accept' class="btn btn-small btn-primary">Accept</a>
<a data-toggle="modal" data-target="#rejectModel" data-id="<%= damage_item.id %>" data-action = 'discuss' class="btn btn-small btn-default">Discuss</a>
</td>
</tr>
<% end %>
<div id="acceptModel" class="modal fade hide" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><%= t('headings.damage_item.accept_damage') %></h4>
</div>
<div class="modal-body" style="max-height: 500px;">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" ><%= t('navigation.buttons.confirm') %></button>
<button type="button" class="btn btn-default" data-dismiss="modal"><%= t('navigation.buttons.cancel') %></button>
</div>
</div>
</div>
Against each item have one accept/discuss button, data_id and data action are data parameter to model pop.
Script
<script type="text/javascript">
var damage_items = '<%= #non_claim_items.only(:id, :estimated_total_repair_cost, :damage_location_name ).to_json.html_safe %>';
$('a[data-toggle=modal]').click(function () {
if (typeof $(this).data('id') !== 'undefined') {
data_id = $(this).data('id');
action = $(this).data('action');
setModelContent($(this), action, data_id)
}
});
function setModelContent(modal, action, data_id) {
if( action == 'accept')
{
// based on action need to set the body of model pop up
}
}
</script>
I need help to write a javascript function that can set the body of model popup as per action.
Based on data_id, need to pick the corresponding data from the damage_items javascript variable, then data stored in the jquery hash need to show in the model popup body.

You can do it like this:
function setModelContent(modal, action, data_id) {
if (action == 'accept') {
// based on action need to set the body of model pop up
}
// Get damage item by data_id
let damage_item = Object.entries(damage_items).filter(item => item[1].id == data_id);
// Creating dynamically bootstrap elements and setting value of inputs by damage_item
let fisrtLabel = $(document.createElement('label')).text('Cost:');
let fistInput = $(document.createElement('input')).addClass('form-control').val(damage_item[0][1].estimated_total_repair_cost);
let firstCol6 = $(document.createElement('div')).addClass('col-sm-6')
.append(fisrtLabel)
.append(fistInput);
let secondLabel = $(document.createElement('label')).text('location name:');
let secondInput = $(document.createElement('input')).addClass('form-control').val(damage_item[0][1].damage_location_name);
let secondCol6 = $(document.createElement('div')).addClass('col-sm-6')
.append(secondLabel)
.append(secondInput);
let formGroup = $(document.createElement('div'))
.addClass('form-group')
.append(firstCol6)
.append(secondCol6);
// Clearing modal-body and filling it by new elements
$('#acceptModel').find('.modal-body').html("").append(formGroup);
}
Online demo (jsFiddle)

Related

Display Data on Dialogbox without reloading page

am trying to display bootstrap dialog box with ID + Name + Price on it.
Then if user choose YES on the dialog, it must hit the Action method where there’s delete function and refresh the data on the page to see the change without reloading the page.
Also I don’t want after it hits the Delete user action method, it must not display its View.
I tried to use ViewBag from the below code but it doesn’t show me the ID + Name + Price on the Bootstrap Dialogbox, and doesn’t redirect to delete action method, and doesn’t refresh the page
#model IEnumerable<School.Models.ApplicationUser>
<hr>
<table class="table table-responsive table-hover">
<tbody>
#foreach (var item in Model.OrderBy(x => x.DateTime))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<span style="color: #ff0000;">
<a class="btn btn-warning btn-sm disclaimer-dialog">
<i class="fa fa-unlock"> </i>Delete
ViewBag.MyId = #item.Id;
</a>
</span>
</td>
#ViewBag.MyId
</tr>
}
</tbody>
</table>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/Views/SchoolAccounts/Delete.js")
}
<!-- Button trigger modal -->
<!-- Modal -->
<div class="modal fade" id="disclaimerModalDialog" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalScrollableTitle">Confirmation Deletion</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p><strong>Are you sure you want to reset password for user ? #ViewBag.MyId </strong></p>
#using (Html.BeginForm("DeleteProduct", "SchoolAccounts",
FormMethod.Post, new
{
#id = "delete-form",
role = "form"
}))
{
#*#Html.HiddenFor(m => m.Id)
#Html.AntiForgeryToken()*#
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
onclick="$('#delete-form').submit();">
Yes
</button>
<button type="button" class="btn btn-primary"
data-dismiss="modal">
No
</button>
</div>
</div>
</div>
</div>
Content of Delete.js
$(function () {
$('.disclaimer-dialog').click(function () {
$('#disclaimerModalDialog').modal('show');
});
});
ViewBag can't be used like that. Once ViewBag is rendered on a page, you can't update its value. All razor variables are static once the page has finished loading.
What we need to do is assign those values on the html attributes.
Modify the link in your loop to have data-properties. I used data-id, data-name, data-price;
#foreach (var item in Model.OrderBy(x => x.DateTime))
{
<tr>
#*just modify the link in the last column*#
<td>
<span style="color: #ff0000;">
<a data-id="#item.Id" data-name="#item.Name" data-price="#item.Price" class="btn btn-warning btn-sm disclaimer-dialog">
<i class="fa fa-unlock"> </i>
Delete
</a>
</span>
</td>
</tr>
}
Modify your Delete.js to access those attributes and replace the content of the modal.
$(function () {
$('.disclaimer-dialog').click(function () {
// get attributes from the button
var id = $(this).data("id");
var name = $(this).data("name");
var price = $(this).data("price");
// Assign value to delete-id
$(".delete-id").val(id);
// update the first paragraph in modal-body
$('#disclaimerModalDialog').find(".modal-body p").eq(0).html("Are you sure you want to delete "+id+"-"+name+"-"+price+"?");
$('#disclaimerModalDialog').modal('show');
});
});
In your modal body, use this for the input field. We need to add a class so we can easily access it;
#Html.HiddenFor(m => m.Id, new { #class="delete-id" });
Add this function to your Delete.js
$(function(){
$("#delete-form").submit(function(e){
// this will stop the page from refreshing or redirecting
e.PreventDefault();
var deleteId = $(".delete-id").val();
var passData = { id:deleteId };
// ajax call here
$.ajax({
type: "POST",
url: "/ControllerName/DeleteAjax",
data: JSON.stringify(passData),
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function(result){
alert(result);
// find the link with data-id == deleteid
// .parent() = span
// .parent().parent() = td
// .parent().parent().parent() = tr
// .remove() = remove that row
$("table a[data-id='"+deleteId+"']").parent().parent().parent().remove();
},
error: function(err){
alert(err);
}
});
});
});
In your controller, add this function. DeleteAjax;
[HttpPost]
public ActionResult DeleteAjax(string id)
{
var product = context.Products.FirstOrDefault(p=>p.Id == id);
if(product == null){
return Content("error, cant find Id")
}else{
context.Products.Remove(product);
context.SaveChanges();
return Content("successfully deleted");
}
}

Modal doesn't come with input's values

I have to use modals in my project. But unfortunately it does not work well.
On the page, when I click on the Add New Role button, everything goes right. But then when I click on the role edit button, the modal is displayed with blank values. While the IDs are successfully sent to the action.
After that when you reload the page, and first click on the edit role button, the modal will not display at all. At the same time, if you click the Add New Role button again, the modal is successfully displayed and everything is OK. At the same time, if you click the role edit button again, the modal will be displayed again in blank. (Just as before the IDs were successfully sent to the action but not found). I think this problem is related to two things:
The problem is with the action (maybe the code I wrote didn't send
the values well)
The problem may be that the following JQuery codes is not
performing well:
Jquery (file name: application-role-index.js):
(function ($) {
function RoleList() {
var $this = this;
function initilizeModel() {
$("#modal-action-application-role").on('loaded.bs.modal', function (e) {
}).on('hidden.bs.modal', function (e) {
$(this).removeData('bs.modal');
});
}
$this.init = function () {
initilizeModel();
}
}
$(function () {
var self = new RoleList();
self.init();
})
}(jQuery))
Anyway i hope you can help me. Here is the code I will use for this section:
Action in 'RoleListController':
[HttpGet]
public async Task<IActionResult> AddEditRole(string Id)
{
RoleListViewModel model = new RoleListViewModel();
if (!string.IsNullOrEmpty(Id))
{
ApplicationRole applicationRole = await _roleManager.FindByIdAsync(Id);
if (applicationRole != null)
{
model.Id = applicationRole.Id;
model.Name = applicationRole.Name;
model.Explanation = applicationRole.Explanation;
}
return PartialView("_AddAndEditAppRole", model);
}
else
{
return PartialView("_AddAndEditAppRole");
}
}
The View page i'm using modal:
<div class="btn-group">
<a class="btn btn-primary" id="showaddrole" data-toggle="modal" asp-action="AddEditRole" data-target="#modal-action-application-role">افزودن نقش جدید</a>
</div>
<table dir="rtl" class="table table-bordered table-striped myTable table-condensed">
<thead>
<tr>
<th>ID</th>
<th>#Html.DisplayNameFor(Model => Model.Name)</th>
<th>#Html.DisplayNameFor(Model => Model.Explanation)</th>
<th>#Html.DisplayNameFor(Model => Model.NumberOfUsers)</th>
<th>عملیات</th>
</tr>
</thead>
<tbody>
#foreach (var role in Model)
{
<tr>
<td>#role.Id</td>
<td>#role.Name</td>
<td>#role.Explanation</td>
<td>#role.NumberOfUsers</td>
<td>
<a class="btn btn-info myTableIC" asp-route-id="#role.Id" asp-action="AddEditRole" data-target="#modal-action-application-role" data-toggle="modal">
<i class="glyphicon glyphicon-pencil"></i>
</a>
<a class="btn btn-danger myTableIC" asp-route-id="#role.Id" asp-action="DeleteRole">
<i class="glyphicon glyphicon glyphicon-remove"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
#Html.Partial("_Modal", new BootstrapModel { ID = "modal-action-application-role", Size = ModalSize.Medium })
#section Scripts{
<script src="~/js/modal-js/application-role-index.js"></script>
}
I have prepared a short video of how my program works so you can move forward with a better understanding:
You can find that by this link...
i suggest a solution at first create a div block with a unique id
<div id="popup"></div>
than use ajax to call the action like this :
$("#btnAdd").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("AddEditRole")',
success: function (result) {
$("#popup").html(result);
$("#popup-addRole").modal("show");
}
});
});
then create an partiel view of popup with the id of model is popup-addRole something like this
<div class="modal" id="popup-edt" role="dialog">
<div class="modal-dialog" role="document" style="width:50%;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
//add your form here
</div>
</div>
</div>
</div>
don't forget to add model you want to use
i hope that fix the problem

Pass object outside of ng-repeat

So I'm new to AngularJs. Currently I'm trying to implement a table filtering and then when I click on the delete button it should delete the right object.
this is how I did it before filtering :
$scope.rowIndex = -1;
$scope.selectRow = function(index) {
if (index == $scope.rowIndex)
$scope.rowIndex = -1;
else
$scope.rowIndex = index;
}
});
In my html :
ng-repeat="session in sessons " ng-class="{'bg-primary':rowIndex == $index }" ng-click="selectRow($index)"
Now after implementing filtering I found out that $index is wrong... So I had to find another way.. I read some articles and all said the same... I just could pass the whole object to the function... But every example did it inside the ng-repeat. Unfortunately... I can't do that since I've a external div for the Modal.
So how do I pass the current selected session / row of the table to the function which is in the modal? {{ deleteSession(session) }}
<div id="deleteSessionModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form>
<div class="modal-header">
<h4 class="modal-title">Delete Session</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete these Records?</p>
<p class="text-warning">
<small>This action cannot be undone.</small>
</p>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<input type="submit" class="btn btn-danger" value="Delete" ng-click="deleteSession(session)">
</div>
</form>
</div>
</div>
</div>
this is how my html / table looks like
you can pass the session as the value to select row function like that:
ng-repeat="session in sessons " ng-class="{'bg-primary':rowIndex == $index }" ng-click="selectRow(session)"
and in the function selectRow, you can take the Id from the session and delete it from the sessions list.
Instead of passing $index to selectRow function, send session.speakerId or another specific unique key of sessions:
ng-click="selectRow(session.speakerId)"
In your controller set/unset selected session:
$scope.selectedSessionSpeakerId = null;
$scope.selectRow = function(sess) {
if (sess == $scope.selectedSessionSpeakerId)
$scope.selectedSessionSpeakerId = null;
else
$scope.selectedSessionSpeakerId = sess;
}
And your deleteSession function does not receive any arguments. It just check the selected Session unique key and delete that from array:
$scope.deleteSession = function() {
if($scope.selectedSessionSpeakerId) {
let index = $scope.sessions.findIndex(finction(itm) {
return itm["speakerId"] == $scope.selectedSessionSpeakerId;
});
$scope.sessions.splice(index, 1);
$scope.selectedSessionSpeakerId = null;
}
}

How to create bootstrap 4 confirmation modal for delete in ASP.NET MVC

I'm having trouble creating bootstrap confirmation modal in ASP.NET MVC. I've managed to successfully call modal when clicking on delete link inside view, but when I want to confirm, nothing happens.
Index View()
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CurrentGrade.GradeName)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Surname)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.CurrentGrade.GradeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Surname)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.StudentId }) |
#Html.ActionLink("Details", "Details", new { id=item.StudentId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.StudentId }, new { #class="element", #data_toggle = "modal", #data_target = "#exampleModalCenter" })
</td>
</tr>
}
</table>
Here is modal that I'm calling:
<div class="modal fade" id="exampleModalCenter" 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">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Are you sure that you want to delete this?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</div>
And finally, here is my simple js script.
$(document).ready(function () {
$('.element').click(function (e) {
$('#exampleModalCenter').modal('show');
if (confirm) {
return true;
} else {
return false;
}
});
});
UPDATE
I tried edit js code according to link that Soham provided but without any luck.
$(document).ready(function () {
$('#exampleModalCenter').on('show.bs.modal', function (e) {
$(this).find('.btn-danger').attr('href', $(e.relatedTarget).data('href'));
$('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-danger').attr('href') + '</strong>');
});
});
Maybe problem lies in #Html.ActionLink for Delete?
#Html.ActionLink("Delete", "Delete", new { id = item.StudentId }, new { #data_toggle = "modal", #data_target = "#exampleModalCenter" })
I was able to reproduce your issue and found some things required to get confirm modal popup work.
Assumed Delete action method exists:
[HttpPost]
public ActionResult Delete(int id)
{
// other stuff
return View();
}
Here are those key points:
1) Add data-id attribute to ActionLink method.
#Html.ActionLink("Delete", "Delete", new { id=item.StudentId }, new { #class="element",
#data_toggle = "modal", #data_target = "#exampleModalCenter",
#data_id = item.StudentId })
2) Add a hidden field which stores value of StudentId to delete.
#Html.Hidden("itemid", "", new { id = "itemid" })
3) Add id element to 'Delete' button in modal popup.
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="Delete" class="btn btn-danger">Delete</button>
</div>
4) Use this script inside document.ready to show modal popup and make request for 'Delete' button click:
$('.element').click(function (e) {
e.preventDefault();
$('#exampleModalCenter').modal('show');
var id = $(this).data('id');
$('#itemid').val(id);
});
$('#Delete').click(function () {
var studentId = $('#itemid').val();
$.post(#Url.Action("Delete", "Delete"), { id: studentId }, function (data) {
// do something after calling delete action method
// this alert box just an example
alert("Deleted StudentId: " + studentId);
});
$('#exampleModalCenter').modal('hide');
});
Live example: .NET Fiddle
Similar issues:
MVC Actionlink & Bootstrap Modal Submit
bootstrap modal for delete confirmation mvc
If you already have the delete action setup in the controller by entity framework, when you added a controller with actions, it should not be complicated, as all what you have to do after the user confirms the delete is to redirect to the delete action view by using simple JavaScript code and a hidden field to hold the item id to pass it in with the URL string.
The bootstrap dialog modal
<!-- Confirmation modal -->
<div class="modal fade" id="confirmdelete" tabindex="-1" role="dialog" aria-labelledby="confirmdelete" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="confirmdelete">Action Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this record ??</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="action">Delete</button>
</div>
</div>
</div>
</div>
Hidden field to hold the item id to be deleted
Make sure it is placed inside the foreach loop
#Html.HiddenFor(c => item.ID, new { #id = "hdnItemId" })
Jquery simple code to redirect to the delete action with item id included
$(document).ready(function () {
$('#action').click(function () {
var itemId = $('#hdnItemId').val();
var actionLink = "/Banks/Delete/" + itemId;
window.location.href = actionLink;
});
});
The above answer is correct and easy but jquery code is supposed to be like this:
$(document).ready(function () {
$('#action').click(function () {
var itemId = $('#hdnItemId').val();
var actionLink = "/MyController/MyDeleteAction?id=" + itemId;
window.location.href = actionLink;
});
});

Bootstrap Modal Confirmation

I've got a table that displays user details per row along with a Remove button that launches a Bootstrap modal confirmation dialog box.
My goal is to have the confirmation button trigger an event which will delete that particular user.
How would I pass jsmith22 from the table row into my Javascript function?
HTML Table
<tr>
<td>jsmith22</td>
<td>John Smith</td>
<td>555-555-5555</td>
<td>test#gmail.com</td>
<td><button type="button" class="btn btn-default btn-lg btn-block roster-button active" data-toggle="modal" data-target="#removeUser">Remove</button></td>
</tr>
Modal dialog
<div aria-labelledby="myModalLabel" class="modal fade" id="removeUser"
role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Remove Employee</h4>
</div>
<div class="modal-body">
<p>Are you sure you wish to remove this user?</p>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal" type="button">Cancel</button>
<button class="btn btn-danger" id="remove-button" type="submit">Remove</button>
</div>
</div><!-- end modal-content -->
</div><!-- end modal-dialog -->
</div><!-- end modal -->
Javascript
// Remove button event trigger
$('#remove-button').click(function() {
$.post('/API/removeUser', {} );
});
Can do it with Bootstrap Modal event listener
Add data attribute data-id to modal trigger button
<td><button type="button" data-id="jsmith22" data-toggle="modal" data-target="#removeUser" class="btn btn-default btn-lg btn-block roster-button active">Remove</button></td>
Add input type="hidden" to modal and pass the id value to modal hidden input when shown
Hidden Input
<input type="hidden" id="RowId" value="">
Modal event show script
$(document).ready(function(){
$('#removeUser').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id');
$('#RowId').val(id);
});
});
Now with click event
$('#remove-button').click(function() {
var delid = $('#RowId').val();
//Do what ever you like to do
$.post('/API/removeUser', {} );
});
Fiddle Example
Alternate Solution
You can skip the hidden input and create a global variable
Modal trigger button with data attribute data-id to modal trigger button
<td><button type="button" data-id="jsmith22" data-toggle="modal" data-target="#removeUser" class="btn btn-default btn-lg btn-block roster-button active">Remove</button></td>
Modal Event, Click function with Global variable script
$(document).ready(function() {
var delid = ''; //global variable
$('#removeUser').on('show.bs.modal', function(e) {
delid = $(e.relatedTarget).data('id'); //fetch value of `data-id` attribute load it to global variable
alert(delid);
});
$('#remove-button').click(function() {
alert(delid); //Use the global variable here to del the record
//Do what ever you like to do
//$.post('/API/removeUser', {} );
});
});
Alternate Solution Example
You can get the contents of the first td of the button's row with getting this:
var person = $(this).closest('tr').find('td').eq(0).html()
fiddle: https://jsfiddle.net/7j4bmgbv/

Categories

Resources