In ASP.NET MVC, what is the preferred pattern for running Javascript on a partial view that is loaded via Ajax?
For example, suppose you need to wire up some click events in your partial view.
Of course, putting something like this in the partial view would not work, because the document ready event won't fire after the partial view is Ajax loaded.
<script type="text/javascript">
$(function() {
$("a.foo").click(function() {
foo();
return false;
});
});
</script>
I suppose something like this might work, but is it safe?
<script type="text/javascript">
$("a.foo").click(function() {
foo();
return false;
});
</script>
The pattern I have been using has been to run any Javascript from my parent view after loading the partial, like this:
$.get(url, function(html) {
$("#partialDiv").html(html);
// Now that the partial has loaded...
RegisterClicks();
});
But I've been working through this example, and noticed that they simply put their click registering code inline in the partial view.
Is this a generally safe pattern to adopt? How can I be sure that the DOM for the partial view has finished loading before my script runs?
The jQuery .on() function should do the trick, shouldn't it? It should work for dynamically added content.
Have this available as part of the full content
<script type="text/javascript">
$(function() {
$("#partialContent").on("click", "a.foo", function() {
foo();
return false;
});
});
</script>
<div id="partialContent">
Link 1
Link 2
<!-- More dynamic content -->
</div>
Scripts are not loaded on Partial view via partial view loaded by ajax in Asp.net MVc
<div class="modal fade" id="myEditCourseModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title text-center">Update Data</h4>
</div>
<div class="modal-body" id="CourseEditPreview">
#Html.Action("CourseUpdatePartial", "AdminCourse")
</div>
</div>
</div>
</div>
<script type="text/javascript">
function OpenCourseEdit(currentId) {
$.ajax({
type: "Get",
url: '#Url.Action("CourseUpdatePartial", "AdminCourse")',
cache: false,
Async: true,
contentType: 'application/html;charset=utf-8',
dataType: "html",
data: { CourseID: currentId },
success: function (data) {
var content = $('#CourseEditPreview').html(data);
eval(content);
$('#myEditCourseModal').modal('show');
},
error: function (error) {
$("#LoadingPanel").css("display", "block");
$('#CourseEditPreview').html("");
}
})
}
</script>
Related
In MinhasVendas2.aspx :
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- dialog body -->
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal">×</button>
Forma de Pagamento
<%-- <%# Eval("desc_tp_pagamento") %>
teste--%>
</div>
<div class="modal-body">
Dados Pagto: <%=id_imobiliaria_pagamento%>
<label id="lblteste"></label>
</div>
<!-- dialog buttons -->
<div class="modal-footer"><button type="button" id="a.btn" class="btn btn-primary"data-dismiss="modal">OK</button></div>
</div>
</div>
</div>
<%--#modalformapagto fim--%>
codebehind:
public void gdvPagamentos_SelectIndexChanged(object sender, EventArgs e)
{
try
{
System.Threading.Thread.Sleep(1000);
List<pagamento> pagto = new List<pagamento>();
var id_imobiliaria_pagamento = gdvPagamentos.SelectedRow.Cells[0].Text;
//ClientScript.RegisterClientScriptBlock(this.GetType(), "", "myModal();", true);
ScriptManager.RegisterStartupScript
(Page,
this.GetType(),
"script",
"myModal();",
true);
}
catch(Exception ex){ }
}
Here is the script being triggered via codebehind:
<script type="text/javascript">
function myModal() {
$("#myModal").modal();
$("#myModal").on("show", function () { // wire up the OK button to dismiss the modal when shown
$("#myModal a.btn").on("click", function (e) {
console.log("button pressed"); // just as an example...
$("#myModal").modal('hide'); // dismiss the dialog
});
})
};
function myModalHide() {
$("#myModal").on("hide", function () { // remove the event listeners when the dialog is dismissed
$("#myModal a.btn").off("click");
})
};
function myModalHidden() {
$("#myModal").on("hidden", function () { // remove the actual elements from the DOM when fully hidden
$("#myModal").remove();
});
$("#myModal").modal({ // wire up the actual modal functionality and show the dialog
"backdrop": "static",
"keyboard": true,
"show": true // ensure the modal is shown immediately
})
}
;
</script>
I declare the variable id_imobiliaria_pagamento also outside the method and the data is recovered normal in codebehind.
But this same variable, with the modal open, and called in the html code inside the modal, shows nothing. Can anybody help me?
In the codebehind, inside the method I had declared the variable in a form (example var xxxxx) and out of the method I had defined as string ... with this was occurring the problem of not displaying it ... Strange that did not accuse error . I corrected for tb string inside the method and the contents of the variables came to be displayed.
I'm using Codeigniter and having trouble on my button after I load my page using load function on jQuery.
reg_form.php loads first, then after saving data, it will load the page-content class to see the list of data but when I'm trying to go to reg_form.php again using the button, nothing happens.
JS is not working on the current loaded page
reg_form.php
<html>
<body>
<div class="page-content">
<label>Name:</label><br>
<input type="text" id="name">
<button id="save"></button>
</div>
</body>
</html>
reg_list.php
<html>
<body>
<div class="page-content">
<button id="reg_form"></button>
</div>
</body>
</html>
reg.js
$('#reg_form').click(function(){
$(".page-content").load('reg_form');
});
$('#save').click(function(){
var name = $('#ame').val();
$.ajax({
url:"gatepass/save",
method: 'POST',
data:{
name:name
},
success:function(data){
$(".page-content").load('reg_list');
}
});
});
Use below mentioned solution.
$(document).on('click','#reg_form',function(){
$(".page-content").load('reg_form');
});
$(document).on('click','#save',function(){
var name = $('#ame').val();
$.ajax({
url:"gatepass/save",
method: 'POST',
data:{
name:name
},
success:function(data){
$(".page-container").load('reg_list');
}
});
});
This will help you.
Tabs and events in the content that you add after the DOM loads should be defined using the .on() function as shown below use of .delegate() has been discontinued:
$(document).on(events,selector,data,eventhandler);
If for example you add the button below into the div after DOM loads and you want the button to say 'You clicked me' when clicked, the code would be:
$(function() {
$(document).on('click', '#justClickMe', function(e) {
alert('You clicked me');
})
$('#content').append('<button id="justClickMe">Just Click Me</button>');
});
<div id="content"><h3>New Content</h3></div>
I am using bootstrap4 alpha 6 Modal, I am getting:
Error: Modal is transitioning
That happen when I am trying to re-trigger the same modal again with dynamic data through JavaScript function as following:
function openModal(title, text) {
$('.modal-title').text(title);
$('.modal-body p').text(text);
$('#modalAlert').modal('show');
}
I tried to use setTimeout function, but didn't work as in this article:
https://github.com/twbs/bootstrap/issues/21687
Any suggestions?
The quickest solution is to remove the modal 'fade' class which is throwing this error. It seems to be a known issue of the Bootsrap v6 that will be fixed in a next released.
See here
Worked with removing fade from parent div class.
Final Modal code ( Adding here for posterity ) :
HTML
<div class="modal loadingModal" id="applemodal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-body">
<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-6">
<img src="ico/4.svg">
</div>
</div>
</div>
</div>
</div>
JS
$.ajax({
type: "GET",
url: "/getTimeline",
data: {
'dateTime': selected
},
async: true,
beforeSend: function () {
$('#applemodal').modal({
backdrop: 'static',
keyboard: false
});
},
success: function(data) {
$('#applemodal').modal('toggle');
}
});
i am using bootstrap 4 Modal too, My solution;
$(document).on('show.bs.modal', '.modal', function (event) {
var zIndex = 1040 + (10 * $('.modal:visible').length);
$(this).css('z-index', zIndex);
setTimeout(function() {
$('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
}, 0);
});
First open the modal and then try to find the DOM elements that's inside modal (eg. $('.modal-title') and $('.modal-body p'))
Changing the order of executing your function might work:
function openModal(title, text) {
$('#modalAlert').modal('show');
$('.modal-title').text(title);
$('.modal-body p').text(text);
}
Finally, make sure that modal is open/visible in the screen when you access HTML that's inside the modal.
Please set your button type='submit' to type='button'
My solution was to open the model programmatically rather than through the link.
Instead of:
Open My Modal
Use:
Open My Modal
$('#myLink').on('click', function(){
$('#myModal').modal('show');
})
I have a page that I have it split in half. The left side will have the text hyperlinks or buttons, and on the right side I need to display the results without page refresh. I'm hoping that bootstrap has something like this but have not been able to find it. Any help will greatly be appreciated.
Bootstrap doesn't provide AJAX calls, it's more for styling your site web. For this, you need to check the jQuery AJAX documentation.
Edit
Here's a simple example to make AJAX calls.
index.php (Basic HTML code)
<div class="container">
<div class="row">
<div class="col-md-6">
<button id="cats" data-animal="cats" class="btn btn-default">Text on cats</button>
<button id="dogs" data-animal="dogs" class="btn btn-default">Text on dogs</button>
</div>
<div class="col-md-6">
<div id="results"></div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="script.js"></script>
script.js (Script where the AJAX call will be made)
$(document).ready(function() {
$("button").on('click', function(e) {
e.preventDefault();
var $this = $(this),
animal = $this.data('animal');
$.ajax({
type: "post",
url: "getAnimal.php",
dataType: "html",
data: { pet : animal },
success: function(data) {
$("#results").html('').html(data);
}
});
});
});
getAnimal.php (PHP script called by AJAX)
<?php
$animal = $_POST['pet'];
if($animal == "cats") {
echo "You clicked on cats!";
}
else if($animal == "dogs") {
echo "You clicked on dogs!";
}
Are these links all in the same domain? If so, it's not too hard to fetch the content at each URL using jQuery's ajax API.
The following javascript code executes in the following order:
1. shows label,
2. shows alert,
3. shows modal;
but the sequence of the commands in the code is different(see code).
In debug mode execution goes in normal order.
What is happening here?
How to get normal order in runtime?
<html>
<head>
<title></title>
<script src="scripts/jquery-2.0.3.js"></script>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<script src="bootstrap/js/bootstrap.js"></script>
</head>
<body>
<input type="file" onchange="openFile(event)"/>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">header</div>
<div class="modal-body">body</div>
<div class="modal-footer">footer</div>
</div>
</div>
</div>
<label id="label" style="display:none;">this is label</label>
<script>
openFile = function (event) {
$('#label')[0].style.display = 'block';
$('#myModal').modal('show');
alert('alert');
}
</script>
</body>
</html>
Use callback of model to run something after model is loaded.
openFile = function (event) {
$('#label')[0].style.display = 'block';
$('#myModal').modal('show');
$('#myModal').on('shown', function() {
alert('alert');
})
}
If Bootstrap 3
openFile = function (event) {
$('#label')[0].style.display = 'block';
$('#myModal').modal('show');
$('#myModal').on('show.bs.modal', function() {
alert('alert');
})
}
Try to use deferred objects if you want to make something happen in an explicit order, since jQuery often kicks events asynchrounusly. With deferred objects you can wait for a function to finish, and then define a callback which will be kicked after the said function is done executing.
The Bootstrap .modal() mechanism (like most of the Bootstrap architecture) drives layout changes via events. To show a modal dialog, the code generates a new Event object and triggers it. That's handled asynchronously by the browser, in that the event handler is invoked in a separate (subsequent) event loop.
Here's the first bit of the modal "show" code in the current github master branch:
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
The handler for that "show.bs.modal" event just adds a class to the <div> involved.