Bootstrap model showing the same text each time - ruby-on-rails

I am using bootstrap modal for showing a popup:
<% #yourphotos.each do |photo| %>
<!-- Modal -->
<div class="modal fade" id="myModal" 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 class="modal-title"><%= name %></h4>
</div>
<div class="modal-body">
<p>
<% if photo.caption != nil %>
<%= photo.caption.text %>
<% else %>
nil text
<% end %>
</p>
</div>
<form class="navbar-form pull-left">
<input type="text" class="span2">
<button type="submit" class="btn">Comment</button>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<% end %>
Lets say I loop through the above and have 10 photos (in #yourphotos) my caption.text in each of the modals when I launch is the same each time even though when I view source I can see the 10 different modal captions..is this a JavaScript thing?

How do you open the modal? Maybe you keep on opening the same modal all the time?

Try one of Following (For bootstrap 3). It will remove the loaded data before open next time.
$( document ).ready(function() {
$("#myModal").on('hidden.bs.modal', function () {
$(this).data('bs.modal', null);
});
});
Or
$( document ).ready(function() {
$('#myModal').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
});
Or
$( document ).ready(function() {
$('#myModal').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
});
Reference Link

Related

How do I access query data in modal popup

This seems like it should be simple but nothing is in ASP.NET Core MVC. I would simply like to present the results of a query in a table inside a modal popup. The modal is opening but the table is empty. Not just that but the table is getting created before I even click the button to show the modal. I'm hoping some kind person out there can help me.
This is the controller action method:
public async Task<IActionResult> GetStudies(int id)
{
var results2 = (from s in _context.Studies
join sn in _context.StudyNodes on s.Id equals sn.StudyId
where sn.NodeId == id
select new BundleNodeViewModel
{
StudyId = s.Id,
StudyName = s.Name
}).ToList();
return Ok(results2);
}
This is the function calling the action:
getStudies = (url, id) => {
$.ajax({
type: 'GET',
url: url,
data: {
'id': id
},
success: function (res) {
console.log(res);
$("#formModal").find(".modal-body").html(res.Name);
$("#formModal").find(".modal-title");
$("#formModal").modal('show');
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
console.log(response);
alert("error");
}
})
};
And this is the modal popup:
<div id="formModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="close_" style="background-color:transparent; color:aquamarine; border-style:none">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Assigned Studies</h4>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col-md-4">
<form asp-action="Bind" asp-controller="Studies">
<div class="form-group">
<table class="table table-hover" style="height: 300px">
<thead>
<tr class="position-sticky" style="color:aliceblue; background-color:#126E75">
<th class="text-start">
Study
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr class=" table-light">
<td class="text-start">
#item.StudyName
</td>
</tr>
}
</tbody>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" id="btnClosePopup" value="Close" data-dismiss="modal" class="btn btn-danger" />
</div>
</div>
</div>
</div>
I'm really confused about the order in which things are happening. For some reason the code in the modal runs when the parent page is loaded and not when you click the button on the parent page to open the modal. So the model in the foreach() statement is not the model I need it to be. When I click on the open modal button I expect it to go to the controller, get the data and return it to the modal where I can loop through the object and create a table.
Any ideas anyone?
I didn't understand your question but I have tried to do what you might want to do.
we have created dummy data which should you get from the ajax.
If you don not want to open the modal on page load please remove the Document Ready part.
try to place the 'getStudies' function body to your ajax's success block.
$(document).ready(()=>{
getStudies();
});
var data = [
{ 'StudyId': 1,'Name':"STD 10"},
{'StudyId' : 2,'Name':"STD 11"}
];
let getStudies = (url, id) => {
$("#formModal").find("tbody").html('');
$.each(data,(index,val) =>
{
let tr=`<tr class="table-light"><td class="text-start">${val.Name}</td></tr>`;
$("#formModal").find("tbody").append(tr);
});
$("#formModal").modal('show');
};
<html>
<head>
<title>kaushal</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body> <button onClick="getStudies()">open modal</button>
<div id="formModal" style="width:100%;border:1px solid red;" class="modal fade in" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="close_" style="background-color:transparent; color:aquamarine; border-style:none">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Assigned Studies</h4>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col-md-4">
<form asp-action="Bind" asp-controller="Studies">
<div class="form-group">
<table class="table table-hover" style="height: 300px">
<thead>
<tr class="position-sticky" style="color:aliceblue; background-color:#126E75">
<th class="text-start">
Study
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" id="btnClosePopup" value="Close" data-dismiss="modal" class="btn btn-danger" />
</div>
</div>
</div>
</div>
</body>
</html>

is it possible to pass Model to Partial View using JavaScript?

I need to pass a Model to a partial view. I first pass a value of ID, then I get the Model I need based on that ID.
The scenario: I have a table with a delete button in each row. I need to display a confirmation bootstrap modal that includes a Model.
The problem, it's not working and I don't know if there another way to do that or not
In the section of javascript BPCategoriesId not recognized
Here is my code attempt.
Delete Button
#foreach (var item in Model.BPCategories)
{
...
<button type="button" data-id="#item.Id" class="btn btn-outline-danger w-50" data-bs-toggle="modal" data-bs-target="#exampleModal">
Delete
</button>
...
}
Bootstrap Modal
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Confirm Delete</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div id="ModelLoad">
<!--here I need to load my partial view with a model using JS-->
</div>
<!--<partial name="Delete" model="#Model.BPCategories.Where(id => id.Id == returnID()).FirstOrDefault()" />-->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<form asp-action="Delete">
<input type="hidden" asp-for="Id" />
</form>
</div>
</div>
</div>
</div>
JavaScript
<script>
$(document).ready(function () {
var btns = document.querySelectorAll('[data-id]');
for (let btn of btns) {
btn.addEventListener('click', () => {
let BPCategoriesId = btn.dataset['id'];
var jsonModel = #Html.Raw(Json.Serialize(#Model.BPCategories.Where(id => id.Id == BPCategoriesId).FirstOrDefault()));
$("#ModelLoad").load('#Url.Action("Delete", "BootstrapCategories")', jsonModel);
});
}
});
</script>
#model LoadPartialView.Models.TestViewModel
#foreach (var item in Model.BPCategories)
{
<p>
<button type="button" data-id="#item.Id" class="btn btn-outline-danger w-50" data-toggle="modal" data-target="#exampleModal">
Delete
</button>
</p>
}
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Confirm Delete</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div id="modelLoad">
<!--here I need to load my partial view with a model using JS-->
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<form asp-action="Delete">
<input type="hidden" asp-for="Id" />
</form>
</div>
</div>
</div>
</div>
#section scripts {
<script type="text/javascript">
$(function () {
var btns = document.querySelectorAll('[data-id]');
for (let btn of btns) {
btn.addEventListener('click', () => {
let bpCategoryId = btn.dataset['id'];
$("#modelLoad")
.load('#Url.Action("Delete", "BootstrapCategories")', {
bpCategories: JSON.parse('#Html.Raw(Json.Encode(Model.BPCategories))'),
bpCategoryId: bpCategoryId
});
});
}
});
</script>
}
Demo is pushed to GitHub.

Pass Variable from View to Model outside of view

How can I pass a variable to my model which is outside the view? The problem is, I had to move the model to application.html.erb because there were z-index conflicts with having the modal code within the products/index.html.erb view.
For example, I'd like to pass the <%= product.id %> variable to the modal popup.
products/index.html.erb
<% products.each do |product| %>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#productDetails" productId="<%= product.id %>">
Launch <%= product.id %>
</button>
<% end %>
layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<%= stylesheet_link_tag 'application' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div id="page-wrapper">
<%= render 'layouts/header' %>
<%= yield %>
<%= render 'layouts/footer' %>
</div>
<!-- Modal -->
<div class="modal fade" id="productDetails" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body product-content">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</body>
</html>
Attempts
I've tried adding javascript to pass the variable, but nothing showed up:
<script>
$('#productDetails').on('show.bs.modal', function(e) {
var $modal = $(this),
productId = e.relatedTarget.productId;
$.ajax({
cache: false,
type: 'POST',
url: 'backend.php',
data: 'EID=' + productId,
success: function(data) {
$modal.find('.product-content').html(productId);
}
});
})
</script>
I've also tried adding a partial within products/index.html, but the modal cannot be called from within products/index.html.erb because of the z-index conflicts.
I don't know what the php part is all about. However, ignoring that part and assuming no one would do something like that, here is how you would handle this in rails:
make the button a remote method call with link_to(something like this):
<% products.each do |product| %>
<%= link_to 'Launch', product, { data: { toggle: 'modal', target: '#productDetails' }, class: 'btn btn-primary btn-lg', remote: true } %>
<% end %>
create js.erb file for show called products/show.js.erb (this assumes #product is defined in controller):
$('#productDetails').html("<%= j render partial: 'show', locals: { product: #product } %>");
move everything from under modal div out into products/_show.html.erb partial:
<div class="modal-dialog" role="document">
<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>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body product-content">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>

UI.bootstrap.modal wont open when using latest versions of libraries

I am trying to do this under ASP.NET MVC 5 Visual Studio 2013, with the latest nuget libraries.
AngularJS Core 1.3.8
AngularJS UI Bootstrap 0.12.0
Bootstrap 3.3.1
jQuery 2.1.3
Important files:
App.js
var deviceModule = angular.module("devicesModule", ["ui.bootstrap"]);
var app = angular.module("dxuWebApp", ["devicesModule"]);
DeviceController.js
deviceModule.controller("DevicesController", function ($scope, deviceService, $modal) {
$scope.devices = [];
function init() {
$scope.devices = deviceService.getDevices();
}
init();
$scope.addDevice = function(size) {
var modalInstance = $modal.open({
templateUrl: "newDeviceTemplate.html",
controller: "NewDeviceModelController",
size: size
});
modalInstance.opened.then(function() {
alert('yep');
});
modalInstance.result.then(function (newDevice) {
deviceService.postDevice(newDevice);
}, function () {
});
}
});
deviceModule.controller("NewDeviceModelController", function ($scope, $modalInstance) {
$scope.ok = function () {
$modalInstance.close({ name: newDevice.name });
};
$scope.cancel = function () {
$modalInstance.dismiss("cancel");
};
});
newDeviceTemplate.html
<div class="modal-header">
<h2>New Device</h2>
</div>
<div class="modal-body">
<input type="text" data-ng-model="newDevice.name" />
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
Index.cshtml
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div data-ng-app="dxuWebApp" data-ng-controller="DevicesController">
<div class="row">
<div class="col-lg-12">
<h2>Devices <a data-ng-click="addDevice()"><span class="glyphicon glyphicon-plus-sign"></span></a></h2>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<ul class="list-inline">
<li data-ng-repeat="device in devices | orderBy: 'name'">
<a href="#">
<div class="device">
<div class="deviceImage">
#*<img alt="device image"/>*#
<span class="glyphicon glyphicon-phone"></span>
</div>
<div class="deviceName">
{{device.name | uppercase}}
</div>
</div>
</a>
</li>
</ul>
</div>
</div>
</div>
#section scripts
{
#Scripts.Render("~/bundles/dxuWebApp")
<script type="text/ng-template" id="newDevice.html">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2>New Device</h2>
</div>
<div class="modal-body">
<input type="text" data-ng-model="newDevice.name" />
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
</div>
</script>
}
The references to both ui-bootstrap and ui-bootstrap.tpls are in the _layout page.
I was hoping that when I clicked
<a data-ng-click="addDevice()"><span class="glyphicon glyphicon-plus-sign">
AngularJs magic would happen and I would get a modal on the screen, but nothing happens, no errors or anything like that.
I did put a break point on deviceController.addDevice() and it hit that point and goes through, nothing appear on the screen.
So what wrong with my code?
I had the exact same problem.
I am using MVC 5.0 with AngularJS so the reason it wasn't working ( I was getting a 404 not able to find the modal.html.) was I didn't create a route in the controller for the modal.html or map a view to the controller with the same name as the route.
After properly setting up the Controller and the View it worked.
Sorry there is no code for this since it was just a problem following the MVC process.

Ruby on Rails AJAX modal doesn't show

I have a problem with AJAX modal window. It just shows grey background, but view doesn't appear.
Link to modal window:
<%= link_to "Create Message", messages_path, remote: true, data: { toggle: "modal", target: "#ajax-modal" } %>
<%= render 'messages/create' %>
Modal window (_create.html.erb):
<div id="ajax-modal" class="modal hide fade" tabindex="-1">
<div class='modal-header'>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Žinutės siuntimas</h3>
</div>
<div class='modal-body'>
<div class="modal-body-content"></div>
<div class="ajax-loader"></div>
</div>
<div class='modal-footer'>
<button type="button" data-dismiss="modal" class="btn">Atšaukti</button>
</div>
</div>
After I click on link, grey transparent background appears, but doesn't show modal window...
Does anyone know why?
The HTML for your modal is malformed, you are missing the modal-content and modal-dialog divs.
<div class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Check this out for more information.

Resources