Closing jQuery Modal dialog after ASP.NET postback opens it again - javascript

I have an HTML link that opens a jQuery modal dialog which contains an iFrame. This iFrame contains a form that should close dialog after postback (Ok or Cancel).
In my postback I add a Javascript function to iFrame that closes the dialog and it works fine. However problem is, after user presses Ok or Cancel button, dialog closes and opens again! What am I doing wrong?
Here is my code:
Calling HTML page:
<html>
<head>
<link rel="stylesheet" type="text/css" href="theme/south-street.css" media="screen" id="themeCSS" />
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript">
$(function () {
$("#dlgConfirm").dialog({
autoOpen: false,
resizable: false,
modal: true,
width: 550,
height: 300,
close: function (event, ui) { alert('closed') }
})
});
function fConfirm(tId) {
alert('ddd');
$('#dlgConfirm').children().attr('src', 'ConfirmTracking.aspx?tId=' + tId)
.load(function () {
$("#dlgConfirm").dialog('open');
});
return false;
}
</script>
</head>
<body>
<div style="display: none">
<div id="dlgConfirm" title="Confirm Tracking" style="padding: 0px">
<iframe style="margin: 0px; padding: 0px" marginheight="0" marginwidth="0" src="" width="100%" height="100%" frameborder="0"></iframe>
</div>
</div>
Click me
</body>
</html>
iFrame Page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ConfirmTracking.aspx.cs" Inherits="Chicken.ConfirmTracking" %>
<html>
<head runat="server">
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript">
function CloseThis() {
parent.$('#dlgConfirm').dialog('close');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<br />
<asp:TextBox ID="edtTrackingNo" runat="server"></asp:TextBox>
<br /><br />
<asp:Button ID="btnOk" runat="server" Text="Ok" />
<asp:Button ID="btnCancel" runat="server" onclick="Cancel_Click" Text="Cancel" />
</form>
</body>
</html>
iFrame Codebehind:
using System;
namespace Chicken {
public partial class ConfirmTracking: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
protected void Cancel_Click(object sender, EventArgs e) {
ClientScript.RegisterClientScriptBlock(this.GetType(), "none", "<script>$(function(){CloseThis()});</script>");
}
}
}

I managed to trace your problem, the load in function fConfirm(tId) triggers again after closing your dialog. It seems to be a bug. A messy way to fix this is adding a global variable to your page and set it to true to show that dialog is opened via function then before opening your dialog if the variable is true open the dialog. don't foget to set your variable to false again so you can re-open dialog if it is needed.
your function will look like below:
var loadedByFunction = false;
function fConfirm(tId) {
loadedByFunction = true;
$('#dlgConfirm').children().attr('src', 'ConfirmTracking.aspx?tId=' + tId)
.load(function () {
if (loadedByFunction) {
loadedByFunction = false;
$("#dlgConfirm").dialog('open');
}
});
return false;
}

Related

Show alert error message when certain condition arises

I have the following code on page load that I use to show an error alert:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["message"] == "noemployees")
AlertDanger.Visible = true;
This is where the error is called. The page reloads and the error is shown.
if (payFitments == null)
{
Response.Redirect("Default?message=noemployees");
}
I have the following markup
<script type="text/javascript">
$(document).ready(function () {
window.setTimeout(function () {
$(".alert").fadeTo(1500, 0).slideUp(500, function () {
$(this).remove();
});
}, 3000);
});
-------------------------
<div runat="server" visible="false" id="AlertDanger" class="alert alert-danger">
×
<strong>You must have at least one employee to process</strong>
</div>
How do I show this message without having to load the default page again? Not seeing examples on the web that show this clearly.
You're using JQuery remove, which effectively deletes the alert from your DOM. So showing it again without reloading your page is not possible.
But you could use JQuery detach instead. Then you can insert it again with appendTo.
var alert = null;
function showHideAlert() {
if (alert) {
alert.appendTo("body");
alert = null;
} else {
alert = $(".alert").detach();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<button onclick="showHideAlert();">Show/Hide alert</button>
<div class="alert">ALERT!!!</div>
</body>
Try serving a static html file and then using the alert function in Javascript. You can learn that here. Example for a button press:
<html>
<head>
<script>
function onError() {
try {
...
} catch (...) {
var error
error = "button was pressed"
alert(error)
}
}
</script>
</head>
<body>
<button id="myButton" onClick="onError()">do not click</button>
</body>
</html>
<html>
<head runat="server">
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge;" /><%-- Also Check Compatible View --%>
<%-- Put all your jQuery... Here I'm showing an example--%>
<script src="//ajax.microsoft.com/ajax/jQuery/jquery-2.1.1.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
window.setTimeout(function() {
$(".alert").fadeTo(1500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
});
</script>
<form id="form1" runat="server">
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
<div runat="server" visible="false" id="AlertDanger" class="alert alert-danger">
× <strong>You must have at
least one employee to process</strong>
</div>
</form>
</body>
</html>
Note:- I think you have missed this... put your jQuery code inside your body tag...

How to Invoke JS function in IFrame from code behind

Asp.Net 4.5 (WebForm)
How can I invoke a js function in Iframe from code behind successfully?
I am using RegisterClientScriptBlock to fire JS function in aspx page that in turn invokes the JS function in html page of iframe.
The Client Button in main page works fine.
The Server Button does not work as intended. However it does recognize the iframe object and contentWindow.
Error
TypeError: Object doesn't support property or method 'TestFunc'
Any constructive help would be appreciated. Note: this is a stripped down example for clarity.
MainPage.aspx
<head runat="server">
<title></title>
<script type="text/javascript">
function InvokeJS(param) {
var iframe = document.getElementById("MyIFrame");
try {
iframe.contentWindow.TestFunc(param);
//=============================================================
//Would really like to use the .apply method over calling the
//function directly. This does work in pure HTML, but not aspx
//=============================================================
//var _ARGS = [];
//_ARGS.push(param);
//iframe.contentWindow('TestFunc').apply(null, _ARGS);
} catch (e) {
alert(e);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="ServerButton" runat="server" Text="Server" />
<input id="ClientButton" type="button" value="Client" onclick="InvokeJS('From Client');" />
<br />
<br />
<iframe id="MyIFrame" runat="server" src="Pages/Test.html" style="width: 700px; height: 300px;"></iframe>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
MainPage.aspx (CodeBehind)
Protected Sub ServerButton_Click(sender As Object, e As EventArgs) Handles ServerButton.Click
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType, "InvokeJS", "InvokeJS('From Server');", True)
End Sub
Test.html (loads into iframe)
<head>
<title>Test</title>
<script type="text/javascript">
function TestFunc(param) {
document.getElementById("DisplayParam").innerHTML = param;
}
</script>
</head>
<body>
<h1>HTML Page</h1>
<h2 id="DisplayParam"></h2>
</body>
</html>
window.onload = TestFunc(); doesn't work because Test.html actually didn't fully loaded before the onload event raised, it's same with ServerButton, because the scriptblock was registered before the test.html loaded. that's why no TestFunc is not available to call.
You can try
<asp:Button ID="ServerButton" runat="server" Text="Server" OnClientClick="InvokeJS('From Server');" />
I don't think you like it if you want it to do something before run the script
Then play this trick
<script type="text/javascript">
//this is help check if postback by Server Button, if yes then invoke
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) {
if (args._postBackElement.id == '<%=ServerButton.ClientID%>')
$('#MyIFrame').load(function(){
InvokeJS('From Client');
console.log('load the iframe');
});
}
</script>

Calling JavaScript Function From CodeBehind doesn't work with FileUpload

I'm creating the following functionality: create table on button click using data from the excel file which was loaded and save this table to xml file. After saving I want to show modal window (bootstrap) with some message. Window managed by javascript function and I called this function from the code behind.
This is my HTML page:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="../js/bootstrap.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="modalSaved" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>
Changes were saved successfully!
</p>
</div>
<div class="modal-footer">
<button type="button" runat="server" id="ok" class="btn btn-default" data-dismiss="modal">OK</button>
</div>
</div>
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<div id="file">
<asp:FileUpload runat="server" ID="OpenFile" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
</div>
<div id="actions" runat="server">
<asp:Button ID="CreateRepBtn" runat="server" OnClick="CreateRepBtn_Click" />
<asp:Button ID="SaveToXml" runat="server" OnClick="SaveToXml_Click" />
</div>
<script type="text/javascript">
function openModalSaved() {
$('#modalSaved').modal('show');
}
</script>
</form>
</body>
And C# code with calling the javascript function:
protected void SaveToXml_Click(object sender, EventArgs e)
{
/* save to xml code */
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModalSaved();", true);
}
The problem is that modal window doesn't appear. I supporse it is connected with FileUpload element somehow because on another page without FileUpload such code works perfect.
I've also tried to use UpdatePanel (FileUpload element was outside) but it doesn't help.
Does anybody know how to solve this problem? Any suggetions are welcome.
protected void SaveToXml_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "$(function(){openModalSaved();});", true);
}
For various your solution may not work, change a bit the implementation and remove script registration from button click callback.
Add in markup hidden placeholder containing client script with call of openModalSaved at document ready:
<script type="text/javascript">
function openModalSaved() {
$('#modalSaved').modal('show');
}
</script>
<asp:PlaceHolder id="plhFileUploaded" runat="server" Visible="false">
<script type="text/javascript">
$(document).ready(function() {
openModalSaved();
});
</script>
<asp:PlaceHolder>
Code behind:
protected void SaveToXml_Click(object sender, EventArgs e)
{
/* save to xml code */
plhFileUploaded.Visible = true;//this will render your placeholder contacting the script
}

why is my ASP.NET button control not firing JQuery Dialog

First of all the button does not fire up the jquery dialog and
When the page loads, i check the console for errors and I get "Uncaught TypeError: undefined is not a function" which is pointing to $("#dialog").dialog({
Here are my codes below.
Default.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="JavaScript1.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CustomValidator runat="server" ID="cv1" ControlToValidate="fupCV" ClientValidationFunction="validate"></asp:CustomValidator>
<asp:FileUpload runat="server" ID="fupCV"/>
<asp:Button runat="server" ID="btnUpload" OnClick="btnUpload_OnClick" Text="Upload"/>
<asp:Button runat="server" ID="btnDialog" OnClientClick="return false;" Text="Open Dialog"/>
</div>
</form>
<div id="dialog" style="display: none">
This is a popup
</div>
</body>
</html>
JavaScript1.js
$(document).ready(function() {
$('#btnUpload').attr('disable', 'disable');
$("#dialog").dialog({
autoOpen: false,
height: 'auto',
width: 350,
modal: true,
resizable: false,
buttons: {
Accept: function () {
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
$(this).dialog("close");
}
});
$("#btnDialog").click(function () {
$("#dialog").dialog("open");
});
});
.dialog() is part of jQuery UI, not jQuery
http://jqueryui.com/dialog/
I don't see jQuery UI included anywhere in your source.
you can use also for id ending something like:
$('input:submit[id$=btnDialog]')).click(function () {});

Jquery Dialog with asp.net

When i click on button to show the message i get one MessageBox that's normal but when i call the Jquery Dialog for the SCOND time i get two MessageBoxs! and when i call Jquery Dialog for the third time i get three MessageBoxs! Please help me!
Here is my Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("[id*=Call_Dialog]").click(function() {
$("#MyDiv").dialog({
title: "jQuery Dialog Popup",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
$("#ShowMessage").click(function () {
event.preventDefault();
alert('Hi');
$("#MyDiv").dialog('close');
})
})
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="MyDiv" style="display: none">
<asp:Button ID="ShowMessage" runat="server" Text="Button" />
</div>
</form>
<p>
<input id="Call_Dialog" type="button" value="button" /></p>
</body>
</html>
Thanks, but how can i call the dialog with button click?
Dialog should be initialized only once not every time you click on something and regenerate
solution is put dialog initialization outside of click and you're done
$(document).ready(function () {
$("#MyDiv").dialog({
title: "jQuery Dialog Popup",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
$("[id*=Call_Dialog]").click(function() {
$("#ShowMessage").click(function () {
event.preventDefault();
alert('Hi');
$("#MyDiv").dialog('close');
})
})
});
to open jquery dialog : use this overload :
$("#MyDiv").dialog('open');

Categories