jQuery dialog + ASP.NET buttons - strange behaviour - asp.net

Having this div:
<div id="advSearchDialog" style="visibility:hidden;">
<xx:search ID="searchUC" runat="server" />
</div>
And a button:
<input type="button" id="btnAdvSearch" value="Search" />
I turn it into a jQuery dialog, where the button opens the dialog:
$(document).ready(function() {
$('#advSearchDialog').dialog({
autoOpen: false,
height: 500,
width: 600,
modal: true,
bgiframe: true,
title: 'Avanceret søgning',
open: function(type, data) {
$(this).parent().appendTo("form");
}
});
$('#btnAdvSearch').click(function() {
$('#advSearchDialog').css('visibility', 'visible');
$('#advSearchDialog').dialog('open');
});
});
Using ASP.NET, I get a problem.
If I push some other button on the ASP.NET page (inside an update panel), and after that clicks the btnAdvSearch button, nothing happens. Why is that?
Thanks in advance

maybe the partial page refresh removes your click event, hard to say without seeing the whole page.
the solutions to that problem would be using jquery live events
http://docs.jquery.com/Events/live
hth

Check the emitted HTML using firebug or somthing similar and you will probably notice that your button is no longer inside the form tags and is at the end of the body tag.
In you're OK button callback you can use something like
dialogBox.appendTo($('#FormIdHere'));
dialogBox is a variable set as so
var dialogBox = $('#DialogDiv').dialog({ autoOpen: false });
This should add your button back into the form.
EDIT:
Here is a code snippet I've recently used (all the code below is fired within an onload function but reasonPostBack must be declared outside the onload function)
var button = $('input.rejectButton');
reasonPostBack = button.attr('onclick');
button.removeAttr('onclick');
var dialogBox = $('#ReasonDiv').dialog({ autoOpen: false, title: 'Please enter a reason', modal: true, bgiframe: true, buttons: { "Ok": function() {
if ($('input.reasonTextBox').val().length > 0) {
$(this).dialog('close');
dialogBox.appendTo($('#theform'));
reasonPostBack();
}
else
{
alert('You must enter a reason for rejection');
}
}
}
});
button.click(function() {
dialogBox.dialog('open');
return false;
});
First i take a reference to the .Net postback with
var reasonPostBack = button.attr('onclick');
and hold it for later then strip the click event from the button to stop the post back ocurring "automatically". I then build the dialog box and add an anonymous function for the OK button, this runs my code to test if there is anything in a text box, if there isn't it simply alerts the user otherwise it;
Closes the div
$(this).dialog('close');
Adds the div back inside the form tags ready for the post back
dialogBox.appendTo($('#theform'));
and then calls the original postback
reasonPostBack();
Finally the last bit of code
button.click(function() {
dialogBox.dialog('open');
return false;
});
adds our own event handler to the .Net button to open the dialog that was instantiated earlier.
HTH
OneSHOT

Related

Why does my jquery-ui modal dialog disappear immediately after it opens?

I'm trying to use a simple jquery-ui modal dialog as a delete confirmation in an ASP.NET C# application. I've done this many times before, but for some reason in this application it is misbehaving. I see the dialog pop up then it immediately disappears before I can click on either "Yes" or "No". Here's the relevant code (Javascript):
<script type="text/javascript" src="/resources/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/resources/jquery-ui-1.9.1.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="/resources/ui-lightness/jquery-ui-1.9.1.custom.css" />
<script type="text/javascript">
var remConfirmed = false;
function ConfirmRemoveDialog(obj, title, dialogText) {
if (!remConfirmed) {
//add the dialog div to the page
$('body').append(String.Format("<div id='confirmRemoveDialog' title='{0}'><p>{1}</p></div>", title, dialogText));
//create the dialog
$('#confirmRemoveDialog').dialog({
modal: true,
resizable: false,
draggable: false,
close: function(event, ui) {
$('body').find('#confirmRemoveDialog').remove();
},
buttons:
{
'Yes, remove it': function() {
$(this).dialog('close');
remConfirmed = true;
if (obj) obj.click();
},
'No, keep it': function() {
$(this).dialog('close');
}
}
});
}
return remConfirmed;
}
//String.Format function (since Javascript doesn't have one built-in
String.Format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
</script>
Here's where I'm using the confirmation function (in the OnClientClick of an <asp:Button> control):
<asp:Button ID="btnRemoveProgram" runat="server" Text="Remove" CausesValidation="false" OnClientClick="ConfirmRemoveDialog(this, 'Please confirm removal', 'Are you sure you wish to remove the selected Program? This cannot be undone.');" />
As I said, I've successfully used this same construct (nearly identical code) many times before; I don't know why it isn't working now. Any ideas will be greatly appreciated, I'm truly stumped on this one.
The runat="server" is telling the button that it should post back to perform events at the server. The OnClientClick will be executed before that on the client side, so you will see the dialog and then immediate the page posts, causing the dialog to disappear.
The problem is that your modal dialog box is not modal in the traditional windows sense. The javascript continues on. The simplest test is to add an alert right before your return, you will see it pops up right after the dialog is shown.
To get around this issue, return false always in the OnContentClick and then in your Yes/No button event handlers use the __doPostback javascript method.
You need to return the remConfirmed to the caller which is the button itself. On your button, do this:
OnClientClick="return ConfirmRemoveDialog(/* the rest of the code */);"

TinyMCE Editor In a jQueryUI Dialog

I have an ASP.NET databound textbox inside a FormView, which I want to display in a jQuery UI dialog with the TinyMCE editor attached to it. I've got it displaying correctly with the editor attached
but when the form is posted back (to be saved to a database), the text inside the editor is lost and does not get posted.
This is the markup of the <div> I'm using for the dialog:
<span id="ExcessiveDutyOfCareWordingDialogLink" style="cursor: hand;">View/Edit Wording</span>
<div id="ExcessiveDutyOfCareWordingDialog" title="Excessive Duty Of Care Wording">
<asp:TextBox runat="server" ID="ExcessiveDutyOfCareWordingTextBox"
Text='<%# Bind("ExcessiveDutyOfCareWording") %>' CssClass="richText" ClientIDMode="Static" />
</div>
and the Javascript I'm using to initialise the dialog and editor, and then actually display it when the <span> is clicked:
$('#ExcessiveDutyOfCareWordingDialog').dialog({ autoOpen: false, height: 300, width: 400, modal: true, resizable: false, buttons: {
Save: function ()
{
// This is from an earlier attempt to fix this problem
// it may be a red herring
tinyMCE.triggerSave();
$(this).dialog("close");
},
Cancel: function ()
{
$(this).dialog("close");
}
}
});
$('#ExcessiveDutyOfCareWordingDialogLink').click(function ()
{
$('#ExcessiveDutyOfCareWordingDialog').dialog('open'); return false;
});
$('.richText').tinymce({
// Location of TinyMCE script
script_url: '/Scripts/tinymce.3.4.5/tiny_mce.js',
theme: "advanced",
theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,cut,copy,paste,|,bullist,numlist,|,undo,redo",
theme_advanced_buttons2: "",
theme_advanced_buttons3: "",
theme_advanced_buttons4: "",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
width: "100%",
height: "20px"
});
Can anyone suggest what I might be doing wrong to explain why I'm losing the text from the editor?
There is actually two problems with the sample code you provided:
1) jQuery dialog actually moves the DOM element (the <div> of your dialog) out of the <form> tag on the rendered document (you can confirm that by looking at the source of the page once it is rendered)
Unless you move the <div> back inside the <form> you will loose the value of the controls inside the dialog on postback.
To fix that, just add the following line of code after the .dialog function definition:
$('#ExcessiveDutyOfCareWordingDialog').parent().appendTo($("form:first"));
2) The "Save" button is rendered as a <span> which will not cause a postback when clicked. If you just want to trigger a postback, you can simply call form.submit() on the page's form.
You code would look something like that:
$('#ExcessiveDutyOfCareWordingDialog').dialog({
autoOpen: false,
height: 300,
width: 400,
modal: true,
resizable: false,
buttons: {
Save: function () {
$('form:first').submit();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$('#ExcessiveDutyOfCareWordingDialog').parent().appendTo($("form:first"));
As solex already stated the div-element gets moved around the DOM. Tinymce doesn ot like such movements and the editor instance will get scrambled leading to the loosing of your context.

jQuery UI Dialog + ASP.NET user control

I'm looking for alternative ways of solving a problem. We're using ElFinder for browsing files, and we want to allow the user to change the access rights to a file element through the right-click context menu ("Change permissions"). The solution I have come up with so far is to load a server side ASP.NET usercontrol in a jQuery modal dialog window. This user control will contain the logic needed to add / remove user access to the selected element.
The jQuery Dialog script looks like this (slightly changed for readability), where DisplayItemAccessConfig() is the method that's called from the context menu:
<!-- access control script -->
<script type="text/javascript" charset="utf-8">
function DisplayItemAccessConfig() {
$.getJSON('AccessRights.ashx', function (data) {
var itemName = data["itemName"];
/* set new title (JUST FOR TESTING) */
$(dialog).dialog('option', 'title', itemName);
/* open modal dialog --> */
$(dialog).dialog('open');
});
}
$(function () {
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: {
"Ok": function () { $(this).dialog("close"); },
"Cancel": function () { $(this).dialog("close"); }
},
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
});
</script>
Challenge 1: find a way to reload the user control each time the jQuery popup is displayed - this is to retrieve the current access settings for the selected element. Now it loads when the page is first loaded, since it's just a div element containing an update panel with a placeholder for my usercontrol and visibility set to none. Anyone have any tips here?
Challenge 2: While I am trying to figure that one out I thought it could be worth while asking for other opinions. Is there a better way of solving this? Should I use a pure jQuery with HTML and call server side .ashx methods to retrieve data, instead of an ASP.NET usercontrol?
You can do this by creating a hidden button on inside the uploadpanel and then trigger it like this:
__doPostBack('<%= Button.ClientID %>','');
Personally I would drop the UpdatePanel and go for jQuery AJAX calls to update the content of the dialog window, but this depends on the complexity of your user control. Hard to say without seeing more of your code.

Append jQuery UI dialog to ASP.NET form on document ready

I have jQuery UI dialog with ASP.NET. I wrap a list of check boxes in the dialog. Since, it's an "Edit page", some of the checkboxes are already checked
because the data fetched from datatbase when page is first loaded.
I have no problem when I click on the link to open dialog, and everything works as expected. However, if I don't click on the link to open dialog, those checkboxes
values will not be picked up from code-behind when form is submitted back. I understand because jQuery UI dialog append "div" to HTML body outside of the "form"
element when the page is loaded.
//I'm trying to append dialog-dept to form on document ready like this but not yet working
$("#dialog-dept").parent().appendTo($("form:first"));
How do I make jQuery UI dialog part of "form" tag required by ASP.NET page when page first loaded?
Because there are many other fields on the page not just those checkbox. Sometime,
there might be no need to open dialog to select any checkbox.
The code below works well only if I click on the link to open the dialog.
$(document).ready(function() {
// Dialog Link
$('#dialog_link_dept').click(function() {
$('#dialog-dept').dialog('open');
return false;
});
// Launch Dialog
$('#dialog-dept').dialog({
autoOpen: false,
width: 700,
modal: true,
open: function(type, data) {
$(this).parent().appendTo("form");
}
});
});
</script>
You can move it into the <form> immediately upon creation, even if it's autoOpen: false, like this:
$('#dialog-dept').dialog({
autoOpen: false,
width: 700,
modal: true
}).parent().appendTo("form");
I guess this way form modal dialog:
$("#dialog-dept").dialog({ height: 300, width: 250, modal: true,appendTo:"form", title: "Title", show: { effect: "fade", duration: 500 }, hide: { effect: "fold", duration: 500} });
and work fine for me

ASP.NET user control and jQuery dialog

On my page I got the following user control:
<div class="editFormDialog" style="display: none; font-size: 12px;">
<mm:Form ID="editUC" ShowCreateButton="false" ShowEditButton="true" runat="server" />
</div>
This UC has a public property that takes a DataSet, and updates some fields in the UC.
So when I push a button on my page, it calls this property on the UC, and the UC gets updated with data from the DataSet.
So far so good. The problem arise when I want the UC to be a jQuery UI Dialog.
First I create the dialog:
$(document).ready(function() {
$('.editFormDialog').dialog({
autoOpen: false,
height: 700,
width: 780,
modal: true,
bgiframe: true,
title: 'Rediger',
open: function(type, data) {
$(this).parent().appendTo("form");
$(this).css('display', 'block');
}
});
});
And I wan't it to open on a button push (this is not an ASP.NET button, plain HTML):
$('#btnEdit').live('click', function() {
$('.editFormDialog').dialog('open');
});
The dialog opens, but the UC does not contain the correct data.
When the page loads, the UC is updated with default data. Then the user clicks a button, and the data changes but the UC isn't updated. It still contains the default data. Thats the problem.
Do you have any idea why?
Help will be much appreciated!
I found the solution for this issue. It turns out that when you append to the form, you need to make sure this snippet of code is inside jquery document ready:
$("#dialog1").parent().appendTo($("form:first"));
So the whole thing should look like this:
jQuery(document).ready(function() {
$("#<%=myFamilyGrid.ClientID %>").tablesorter({
sortList: [[0, 1]]
})
.tablesorterPager({ container: $("#pager") });
$("#dialog1").dialog({
modal: true,
height: 370,
width: "350px",
autoOpen: false,
bgiframe: false,
zIndex: 3999
});
$("#dialog1").parent().appendTo($("form:first"));
});
Hope this helps!
Exactly what happens when you "call the property" (I would assume you mean it's a method)? Does the page perform a postback? If that's the case, maybe the postback is getting blocked somehow when you mix jQuery into the scenario?
Since you are using Update Panels, how are you injecting the call to the javascript in the page? I ask, because there's only one way that work properly on partial postbacks: ScriptManager.RegisterStartupScript(). That allows javascript code to act as if the page was loaded. Of course any other onload javascript may be called too, which may result in the behavior you are seeing.
So,
make sure that your javascript is injected with the script manager.
make sure only the bits of javascript that you want to execute
after a partial postback are
executed
There is also the possibility of turning your UC in a ajax control with a web service to change the datasource. No more partial postbacks then, which usually improve the responsiveness of the page.

Resources