ASP.Net Ajax client side script, accessing source - asp.net

I've seen in quite a few examples of asp.net ajax client side script the following:
function fHelloWorld(source, eventArgs)
{
}
If I run an alert on the source it's returned as an object. Can I use this to access what called the function? And if so how? i've tried things like
source.id;
Without luck

The best advice that I can offer is, given an object, enumerate over the properties and write them out, including their values to the page. Then inspect the property values and will surely find out if such a property exists. You could also use Firebug, Fiddler2 or host of other tools to inspect the object.
Here's an example
function pageLoad(sender, args) {
// add function to the PageRequestManager to be executed on async postback initialize
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
}
function InitializeRequest(sender, args) {
// Display loader gif when async postback initialized by element_in_question
if(args._postBackElement.id === 'id_of_element_in_question' {
$get('ajax-loader').style.display = 'inline';
}
}

Run the page with Firefox & Firebug, set a breakpoint inside your function, and inspect the source object interactively.
You can also display the object with console.log to get an object inspection hyperlink:
function fHelloWorld(source, eventArgs)
{
console.log("%o", source);
}

Related

How to get the id of Updatepanel which is about to start a postback

I need to get the id of the panel that is about to start a postback, so I have a generic way to block ui on this panel.
So far I have this function:
function BeginRequestHandler(sender, args) {
$('#' + args.get_updatePanelsToUpdate()[0]).block({ message: null });
}
attached like this:
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
this works pretty well to get the id if control that causes partial postback is inside update panel, but if it is outside (using a trigger), args.get_updatePanelsToUpdate() is always null
I've seen this answer, but it wont work forme because function is fired after partial postback is complete, I need it before..
Thank you
So here's what I did:
created 2 functions to block (on partial postback begin) and unblock (on partial postback end):
function BeginRequestHandler(sender, args) {
$('#' +sender._postBackSettings.panelsToUpdate[0].ReplaceAll('$', '_')).block({ message: 'loading...' });
}
function EndRequestHandler(sender, args) {
$('#' + sender._postBackSettings.panelsToUpdate[0].ReplaceAll('$', '_')).unblock();
}
Registered above functions on my page right after my script manager:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
</script>
Some conditions:
I'm using jquery UI block plugin but you should use what better fits your needs.
You update panels should have ClientIDMode="AutoID" if your using .NET 4.0 +
I used the following helper function cause js doesn't make a real replace all and to deal with asp net autoID's:
String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
If you just want to disable (or animate in some other way) the UpdatePanel, why not just use UpdatePanelAnimation? It provides you with the following hooks (not sure if that's the right word):
OnUpdating - Generic animation played as when any UpdatePanel begins
updating
OnUpdated - Generic animation played after the UpdatePanel
has finished updating (but only if the UpdatePanel was changed)

Display jquery dialog on postback in ASP.NET after saving a new record

What I would like to do is have the user add a new record to the database and popup a JQuery dialog confirming that the new record was saved. I thought this would be a simple exercise. I have a gridview bound to a LINQDataSource to allow the user to view and edit existing records and a textbox and a button to add new codes.
In the head of the document, I have the following:
$('#dialog').dialog({
autoOpen: false,
width: 400,
buttons: {
"Ok": function () {
$(this).dialog("close");
}
}
});
and futher down in the markup I have:
<div id="dialog" title="New Code Added">
<p>"<asp:Literal runat="server" ID="LiteralNewCode"></asp:Literal>" was successfully added.</p>
</div>
So when the user enters a new description and it passes all the validation, it's added to the database and the gridview is rebound to display the new record.
protected void ButtonSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CCRCode.Add( <long list of paramters> );
GridCode.DataBind();
IsNewCode = true;
NewDescription = <new description saved to database>;
}
}
Now, here's where (I thought) I'd set a boolean property to indicate that a new description had been added as well as the text of the new description. See below:
protected bool IsNewCode
{
get { return ViewState["IsNewCode"] != null ? (bool)ViewState["IsNewCode"] : false; }
set { ViewState["IsNewCode"] = value; }
}
private string NewDescription
{
get { return ViewState["NewDescription"] != null ? ViewState["NewDescription"].ToString() : string.Empty; }
set { ViewState["NewDescription"] = value; }
}
Here's where I loose my way. My guess is I want to add functionality to include code similar to:
$('#dialog').dialog('open');
I've added a registerscriptblock method in the page_load event but that didn't work. Any ideas? Or am I just going about this entirely wrong?
Thanks.
Not really get what you want to do. But, i use jquery alot with .NET in my projects. here is how i do, probably could give you a hint.
foo.aspx.cs
public String ScriptToRun = "$('#dialog').dialog('open');";
change the value of ScriptToRun in your C# code
foo.aspx
$(document).ready(function() {<%=ScriptToRun %>});
Remember that whatever you done in backend is going to generate HTML, Css& javascript to browser.
Two ways: one, write the javascript in your server-side code. Or, define a JS method to show the dialog (say named showDialog), and call it via:
Page.ClientScript.RegisterStartupScript(... "showDialog();" ..);
RegisterStartupScript puts the method call at the end, ensure your script is above it to work. You can also wrap it with document.ready call too, to ensure JQuery is properly loaded.
I think that the only think that you have miss is the creation of the dialog when the Dom is ready.
$(document).ready(function() {$('#dialog').dialog('open');});
I posted code in a different question for a custom "MessageBox" class I wrote:
ASP.NET Jquery C# MessageBox.Show dialog uh...issue
the code by default uses the javascript alert() function, but you can define your callback so that it calls your custom javascript method to display the messages.

Passing arguments from one asp.net page to another using jQuery

I need to pass 4 arguments (3 strings and one comma separated list) from an ASP.NET page to another ASP.NET page using jQuery. The destination page ought to be launched as a separate window, which works fine with the following jQuery snippet:
$('#sourcePageBtn').click(function(){
window.open("destinationPage.aspx");
return false;
});
How can I pass the arguments to the destination page? I am trying to avoid the query string to pass the arguments because:
I don't want to show the url arguments (which can also be very long) in the destination window.
There are some special characters like ',/,\, & etc. in the string arguments.
Please suggest.
Edit:
I'm trying to access the arguments in the script section of the aspx file i.e.
<script language="C#" runat="server">
protected void Page_Load ( object src, EventArgs e)
{
//Creating dynamic asp controls here
}
</script>
My specific need for the arguments in the Page_Load of the script section stems from the fact that I am creating a few dynamic Chart controls in the Page_Load which depend on these arguments.
cheers
Initial Thoughts (before solution created)
Use POST for large data instead of GET. With POST no querystring will be used for data and therefore URL length restriction isn't a concern. (The max URL length differs between browsers so you're right to stay away from it when large data is moving).
Special URL characters can be encoded to be passed in the query string so that shouldn't be an issue.
Alternatively you might store the data on the server side from the first page, and have the second page pick it up from the server side. But this is overkill. And it makes you do unneeded server programming.
Passing state via HTTP calls is standard practice. You shouldn't try to circumvent it. Work with it. All the facilities are built in for you. Now it's just up to jQuery to provide us some help...
Note: Be careful using jQuery for main app features in case JavaScript is disabled in the browser. In most cases your web application should be usable at a basic level even when JavaScript is disabled. After that's working, layer on JavaScript/jQuery to make the experience even better, even awesome.
Edit: Solution (with ASP.NET processing)
Key resources for solution implementation are:
How use POST from jQuery - initiates the request, passes arguments, gets response
jQuery context argument - this is how the popup window DOM is accessed/affected from the main window
How it works: From a main page, a POST occurs and results are displayed in a popup window. It happens in this order:
The main script opens a popup window (if it doesn't already exist)
main script waits for popup window to fully initialize
main script POSTs (using AJAX) arguments to another page (sends a request)
main script receives response and displays it in the popup window.
Effectively we have posted data to a popup window and passed arguments to the processing.
Three pages follow and they constitute the complete solution. I had all 3 sitting on my desktop and it works in Google Chrome stable version 3.0.195.38. Other browsers untested. You'll also need jquery-1.3.2.js sitting in the same folder.
main_page.html
This is the expansion of the logic you provided. Sample uses a link instead of a form button, but it has the same id=sourcePageBtn.
This sample passes two key/value pairs when the POST occurs (just for example). You will pass key/value pairs of your choice in this place.
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
</head>
<body>
<a id="sourcePageBtn" href="javascript:void(0);">click to launch popup window</a>
<script>
$(function() {
$('#sourcePageBtn').click( function() {
// Open popup window if not already open, and store its handle into jQuery data.
($(window).data('popup') && !$(window).data('popup').closed)
|| $(window).data('popup', window.open('popup.html','MyPopupWin'));
// Reference the popup window handle.
var wndPop = $(window).data('popup');
// Waits until popup is loaded and ready, then starts using it
(waitAndPost = function() {
// If popup not loaded, Wait for 200 more milliseconds before retrying
if (!wndPop || !wndPop['ready'])
setTimeout(waitAndPost, 200);
else {
// Logic to post (pass args) and display result in popup window...
// POST args name=John, time=2pm to the process.aspx page...
$.post('process.aspx', { name: "John", time: "2pm" }, function(data) {
// and display the response in the popup window <P> element.
$('p',wndPop.document).html(data);
});
}
})(); //First call to the waitAndPost() function.
});
});
</script>
</body>
</html>
popup.html
This is the popup window that is targeted from the main page. You'll see a reference to popup.html in the jQuery script back in the main page.
There's a "trick" here to set window['ready'] = true when the popup window DOM is finally loaded. The main script keeps checking and waiting until this popup is ready.
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
</head>
<body>
<!-- The example P element to display HTTP response inside -->
<p>page is loaded</p>
</body>
<script>
$(function() {
window['ready'] = true;
});
</script>
</html>
process.aspx.cs (C# - ASP.NET process.aspx page)
The dynamic server page the arguments are POSTed to by the main page script.
The AJAX arguments arrive in the Page.Request collection.
The output is delivered back as plain text for this example, but you can customize the response for your apps requirements.
public partial class process : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
// Access "name" argument.
string strName = Request["name"] ?? "(no name)";
// Access "time" argument.
string strTime = Request["time"] ?? "(no time)";
Response.ContentType = "text/plain";
Response.Write(string.Format("{0} arrives at {1}", strName, strTime));
}
protected override void Render(System.Web.UI.HtmlTextWriter writer) {
// Just to suppress Page from outputting extraneous HTML tags.
//base.Render(writer); //don't run.
}
}
Results of this are displayed into the popup window by the original/main page.
So the contents of the popup window are overwritten with "[name] arrives at [time]"
Main References: HTTP Made Really Easy, jQuery Ajax members and examples.
If you keep a reference to the new window when you open it, ie var destWin = window.open(...) then you can access the variables and methods on the destWin window object. Alternatively you can "reach back" from the destination window with window.opener.

ASP.NET - UpdatePanel and JavaScript

Is there a way to execute script when an UpdatePanel process is finished.
I have a page that allows "inserting", "copying", and "editing" of a record.
This is all done on an UpdatePanel to prevent a page navigation.
Somewhere else on the page I would like to print a "flash" message - like "You have successfully entered a record." It is not near the UpdatePanel and I'd like to use a jQuery effect on the message so it fades out after 4 seconds. How can I send script back with the UpdatePanel or have it execute after a UpdatePanel refresh? Should I write script to an asp:literal? thoughts?
Yes:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
And then:
function endRequestHandler(sender, args)
{
// Do stuff
}
Documentation here and here. Keep in mind that this will fire for every AJAX request on the page.
This should do the trick:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args)
{
//Jquery Call
}
function EndRequestHandler(sender, args)
{
//Jquery Call
}
</script>
Here is an article for how to do it using ScriptManager's static method RegisterClientScriptBlock. Tried it and works like a charm.
http://csharperimage.jeremylikness.com/2009/06/inject-dynamic-javascript-into-aspnet.html
var requestManager = Sys.WebForms.PageRequestManager.getInstance();
requestManager.add_beginRequest(function () { alert('here1') });
requestManager.add_endRequest(function () { alert(here2') });
Source: http://www.howtositecore.com/?p=36
The Sys.WebForms.PageRequestManager.getInstance() method works great for me as well.
I work with a lot of pages that contain multiple Updatepanels and I've learned that this will automatically fire even if the Updatepanel you don't want it for refreshes. So inside the function that fires on the event make sure you have something like:
function BeginRequestHandler(sender, args) {
if (args.get_postBackElement().id == "ID of the Updatepanel") {
// do stuff here
Bruno,
First, to answer your direct question. In your callback that is being called by the update panel, you should be able to use a RegisterStartupScript call to invoke a JS method . Then in your JS method, you would show the message and then you can use do a:
setTimeout('$('#myMessage').fadeOut("slow")', 4000);
to have it fade away after 4 seconds.
To go one step further, since you're already implementing JavaScript, I would invite you to check out this article about UpdatePanels. If possible, I would try to send Ajax calls to do your inserting, copying, and editing and this would further simplify your user feedback and would prevent excess info across the wire.

How do I run client script after a postback?

I'm looking for something like OnClientClick for a button, but I want it to happen after the postback (instead of before). I'm currently using the following, which works, but it adds the script block over and over again, which is not what I want. I simply want to execute an existing client script function.
ScriptManager.RegisterClientScriptBlock(
this,
typeof( MyList ),
"blah",
"DraggifyLists();",
true );
If you're using ASP.NET AJAX, you could try the following:
addRequestHandler() must be called when your page loads
function addRequestHandler()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
function endRequestHandler(sender, args)
{
// This function will be called after the postback has completed
// add your JavaScript function call here
}
This is based on code from Disturbed Budda

Resources