ASP.NET user control and jQuery dialog - asp.net

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.

Related

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.

asp.net mvc JavaScript in View User Controls rendered through regular browser request and AJAX request

I have this code in some of my ASCX files:
<%=Html.ActionLink(Resources.Localize.Routes_WidgetsEdit, "Edit", "Widget",
new { contentType = Model.ContentType, widgetSlug = Model.Slug, modal=true},
new
{
rel = "shadowbox;height=600;width=700",
title = Resources.Localize.Routes_WidgetsEdit,
#class = "editWidget"
})%>
Take note of that rel="shadowbox..." there. This is to wire up ShadowBox Lightbox clone for this ActionLink.
This works fine when user requests a page containing this User Control thru normal browser request. But I also render/build those View User controls trough AJAX requests. For instance, I would make request to /Widget/RenderToString/... using jQuery .ajax() method and it would return HTML code for that control. This works fine and it renders the code fine. I would then insert (append) the result to a DIV in a page from where the AJAX request was made. This also works fine and the returned HTML gets appended. The only problem is - ShadowBox is not wired up. Even though the code for it gets rendered.
It seems it requires page reload (F5) every time to wire ShadowBox up. Since I am doing AJAX GET and instant append to get rid of having to make a server roundtrip, I would also want ShadowBox to wire up without doing refresh.
Can someone help me with that? Thank you
UPDATE:
Yes, I have this in my Site.Master head:
<script src="<%=Url.Content("~/Scripts/shadowbox-build-3.0rc1/shadowbox.js") %>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
// insert functions calls here that provide some default behaviour
externalLinks();
});
Shadowbox.init({
language: "en",
players: ["img", "html", "iframe"],
onClose: function() { location.reload(true) }
});
</script>
How do I init the Shadowbox again after AJAX call?
There are many shadowbox plugins... which one are you using? (I can't give you exact code without it.) In any case I imagine you have something in your $(document).ready(function () { ... }); that tells shadowbox plungin to bind itself. You need to call that again after the AJAX call.
Just found the solution here
// call this after adding the new HTML to the page
// set up all anchor elements with a "editWidget" class to work with Shadowbox
Shadowbox.setup("a.editWidget", {});

Modal Window When Clicking Link Button

I have a LinkButton inside a data list. When I click on this LinkButton, I want to open a modal window and load another html page in it.
Can you guys please help me with this?
You should check out a jQuery plugin like Thickbox, which I've used to do exactly what you've described.
check ModalPopupExtender....It's a component of Ajax Control toolkit.
First download it from from CodePlex ....and when you add reference the *Binary.dll to your project...you can use it within your pages.
I have always been a big fan of YUI, they have great documentation and Examples showing how to set things up. [ i love jQuery too ].
Look at YUI's Container Objects. They have very slick skinable Modal Panels:
http://developer.yahoo.com/yui/container/panel/
Here is a simple example:
http://developer.yahoo.com/yui/examples/container/panel-loading.html
Server Side
button.Attributes.Add("click", "popModal");
Client Side
<script>
function popModal(e) {
// Initialize the temporary Panel to display while waiting for external content to load
var SavingPanel =
new YAHOO.widget.Panel("wait",
{ width: "240px",
fixedcenter: true,
close: false,
draggable: false,
zindex: 1000,
modal: true,
visible: true
}
);
SavingPanel.setHeader("Saving, please wait...");
SavingPanel.setBody('<img src="http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif" />');
SavingPanel.render(document.body);
}
</script>

jQuery dialog + ASP.NET buttons - strange behaviour

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

How do I interrupt an ASP.NET button postback with BlockUI and Jquery

I have an ASP.NET page with a number of ASP:Button instances on it. For some, I need to show a confirmation prompt and, should the user choose yes, the original postback method is called. Otherwise, the overall process is cancelled.
I've got an example running but I get inconsistent results, mainly in FF3 where I get an exception thrown:
[Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame ::
I've looked this error up but I'm drawing a loss as to where I'm going wrong. Here's my example case. Note, for now I'm just using the css class as a lookup. Longer term I can embed the clientID of the control into my JS if it proves necessary :).
Html fragment:
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStartClicked" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).get()[0].click);
$(this).unbind("click");
}).click(function(){
var oldclick = $(document).data("startclick");
alert("hello");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
return false;
});
My code behind is relatively simple, the OnStart method simply executes a Response.Write
I've only just started looking into bind, unbind and trigger so my usage here is pretty much 'first time'.
Thanks for any help or advice.
S
EDIT:
This describes what I'm trying to do and also gives a run down of the kind of pitfalls:
http://www.nabble.com/onClick-prepend-td15194791s27240.html
How about this?
$(document).ready( function() {
$('.startbutton').click(function() {
return confirm('Are you sure?');
})
});
I've solved my problem for IE7 and FF3.
The trick is to make the postback work as an 'onclick' via an ASP.NET attribute on the button (see below). In Javascript this gets pulled out as a function reference when you read the click in JQuery.
To make it work, you then clear the onclick attribute (after saving it) and call it later on.
My code below shows it in action. This code isn't complete as I'm part way through making this into a generic prompt for my application. Its also a bit badly laid out! But at least it shows the principle.
ASP.NET button
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStart" UseSubmitBehavior="false" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).attr("onclick"));
$(this).removeAttr("onclick");
}).click(function(){
$.blockUI({ message: $('#confirm'), css: { width: '383', cursor: 'auto' } });
$("#yes").click(function(){
$.unblockUI();
var oldclick = $(document).data("startclick");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
});
$("#no").click(function(){
$.unblockUI();
});
return false;
});
Your problem comes from here :
$(document).data("startclick", $(this).get()[0].click);
...
var oldclick = $(document).data("startclick");
...
oldclick();
Here, you try to intercept a native event listener but there are two errors :
Using unbind will not remove the native event listener, just the ones added with jQuery
click is, AFAIK, a IE only method used to simulate a click, it not the event handler itself
You'll have to use onclick instead set its value to null instead of using unbind. Finally, don't store it in $(document).data(...), you'll have some problems when you add other buttons. Here is a sample code you can use :
$("selector").each(function()
{
var oldclick = this.onclick;
this.onclick = null;
$(this).click(function()
{
if (confirm("yes or no ?")) oldclick();
});
});
for mi works:
this.OnClientClick = "$.blockUI({ message: $('#ConfirmacionBOX'), css: { width: '275px' } });return false;";
This is a button (is a button class)

Resources