Showing posts with label net. Show all posts
Showing posts with label net. Show all posts

Wednesday, March 28, 2012

Calling jvascript function from the button under UpdatePanel

Hello,

I am having a a web application developed using asp.net2.0 with vb.net as a language.

In this web application i am having two buttons and one update panel. Now my button1 is outside the updatepanel and another button2 is present inside the updatepanel.

In asp.net if we want to run any javascript function on the click of a button then we normally use the button.attribute.add() function but if we want that when user click on button then first some server side code will be performed and then the javascript function will be called.

For that we uses the below code in asp.net !!!

Page.ClientScript.RegisterClientScriptBlock(Me.GetType,"Script", "<Script>alert('Hello');</Script>")

this code is working fine on the click event of the button that is present outside the update panel. But when i am running the same code on the click event of the button that is present inside the updatepanel then its not working,

Remeber that i d't want to run the javascript code when user just click on the button , i want first some server side code wil perform his work then after this script will run.

But for controls under update panel its not working.??

please paste your code here, because I am doing almost the same thing here without any issues.


Hi,

Add a Literal control to your web form.

In your Click method use this code:

literal1.Text = "<script type=\"text/javascript\"> alert('Hello world!');</script>";

Dont forget to clear Text property in another postbacks.


Use ScriptManager.RegisterStartupScript, instead of the ClientScript class' method.


Can anyone tell me the solution for this?

Me too getting the same issue.

Thanks,

Jasmeeta.

Calling javascript when a page has refreshed

I have an AJAX app that needs to call a javascript function when the page changes its state (for example some panels are hidden/displayed).

Due to the nature of AJAX, I can't use window.onload since no load event occurs.

What can I use to call my javascript functions when the page content changes?

If you are using UpdatePanels you can handle the PageRequestManager events:

http://ajax.asp.net/docs/ClientReference/Sys.WebForms/PageRequestManagerClass/default.aspx


It worked!

I had a javascript function called adjustHeight.


I added

<head>... <script type="text/javascript"> function adjustHeight() { . . . } window.onLoad = function() { Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(adjustHeight); } </script>

calling javascript proxy functions from master.pages

I 've a master page with an scriptmanager with EnablePAgeMethods=true.

I want to call from that page a static methode from my page within client side with a call like PageMethods.DeleteFIle()-this beeing a javascript proxy class which supoused to be generated by the script manager.

The issue is that this call work well from a simple page but not from master page -on java script i 've got the PageMaster it's unknown.

Thank you

Hi,

Here is a sample made according to your requirement. Please try it:

[Master page]

<%@. Master Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"></script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title> </head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager> <input id="Button1" type="button" value="button" onclick="SayHello();"/> <input id="Text1" type="text" /> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> </div> <script type="text/javascript"> function SayHello() { PageMethods.Hello(onComplete); } function onComplete(result) { $get("Text1").value = result; } </script> </form></body></html>

[Content page]

<%@. Page Language="C#" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %><script runat="server"> protected void Page_Load(object sender, EventArgs e) { } [System.Web.Services.WebMethod] public static string Hello() { return "Hello world!"; }</script><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"></asp:Content>
Hope this helps.

I have nearly this exact scenario, but the result returned is always the complete markup for the page. Any ideas as to why this is?


Can you show me your code

I also have the same problem. The pagemethod callback shows full page markup instead of return value.

Here's the code

<%-- <Snippet1 Master page> --%>

<%@.MasterCodeFile="MasterPage.master.cs"Inherits="MasterPage"Language="C#" %>

<%@.RegisterAssembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

Namespace="System.Web.UI"TagPrefix="asp" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headid="Head1"runat="server">

<title>UpdatePanel in Master Pages</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<pstyle="font-family: Playbill, Fantasy; background-color: olive; font-weight: bold;

font-size: xx-large;">

Master Page

</p>

<hr/>

<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="true">

</asp:ScriptManager>

<hr/>

<br/>

<asp:ContentPlaceHolderID="ContentPlaceHolder1"runat="server">

</asp:ContentPlaceHolder>

</div>

</form>

</body>

</html>

<%-- </Snippet1> --%>

<%-- <Snippent2 Child content page> --%>

<%@.PageCodeFile="Child.aspx.cs"Inherits="Child"Language="C#"MasterPageFile="MasterPage.master"

Title="UpdatePanel in Master Pages" %>

<%@.RegisterAssembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

Namespace="System.Web.UI"TagPrefix="asp" %>

<asp:ContentID="Content1"runat="Server"ContentPlaceHolderID="ContentPlaceHolder1">

<pstyle="font-family: Playbill, Fantasy; background-color: aqua; font-weight: bold; font-size: xx-large;"> Content Page</p>

<hr/>

<scripttype="text/javascript">

function doload()

{

PageMethods.GetName(GetName_Complete);

}

function GetName_Complete()

{

if(arguments.length >0)

{

alert(arguments[0].toString());

//document.getElementById('<%=txt1.ClientID %>').value = arguments[0].toString();

}

}

</script>

<asp:TextBoxID="txt1"runat="server"></asp:TextBox>

<inputid="Button2"onclick="doload()"type="button"value="button"/><br/>

<br/>

<asp:UpdatePanelid="UpdatePanel2"runat="server">

<contenttemplate>

<asp:TextBoxid="txtChild"runat="server"></asp:TextBox>

</contenttemplate>

<triggers>

<asp:AsyncPostBackTriggerControlID="lnkChild"EventName="Click"></asp:AsyncPostBackTrigger>

</triggers>

</asp:UpdatePanel>

<asp:ButtonID="lnkChild"runat="server"OnClick="lnkChild_Click"Text="Ajax Update"/>

<hr/>

</asp:Content>

calling javascript in atlas

Hi,

I want to call a javascript function when call is made to server using atlas.

For e.g. instead of using ProgressBar of atlas which makes a div tag visible till server response comes in,I want to do some other processing through a javascript function till server response comes in (like hiding button).

Is it possible ?

thanks in advance for response

hello.

yes, you can...search this forum for pagerequestmanager _inPostback...you should find 1 or 2 examples that show how to do that.

calling javascript functions

I am working on an ajax web page which has several controls including a ScriptManager control and the ajax Timer control. When the timer fires a tick I want the server side to perform some calculations and then call a client script function with the results. The client script will then do something with the results.

Also, I want to call another javascript function when I click a button.

I'm a bit rusty with javascript, so I'd like to see examples on how to make this work.

What and where exactly you want to do?

When the timer fires, I want the server to generate (calculate) a pair of integers (or possibly an array of pairs) and call a javascript function on the client side passing those numbers. The client will then "plot" points on a graphics window using some built-in drawing java functions I have. The timer will probably fire several times a second. The client does not need to make any calls to the server.

When a button is clicked, I want the server to call another javascript function (passing no arguments) which will erase the graphics window. The timer continues firing.

I have other buttons, to start and stop the timer, sliders to change the timer rate and other parameters, checkboxes and radio buttons which also affect the calculations, etc. All I need help with is making the client calls and passing the data. Is the ScriptManager useful in that respect? By the way, I'm kind of "new" in java.

I've seen scenarios where client calls server, and server calls the client back with a reply. However, can the server just call the client repeatedly? Or does the timer control act as the client-to-server caller?


Yo can use for calling javascript function

Registering Custom Script

from ScriptManager

http://ajax.asp.net/docs/mref/O_T_System_Web_UI_ScriptManager_RegisterClientScriptBlock.aspx

For calling server side function use web services..


Actually, what I need to do requires "COMET", a form of "reverse AJAX". Is there an easy way to emplement COMET in ASP.Net? When the user clicks the "start" button, the server needs to begin "firing" pairs of numbers at the client at a steady rate (several times a second) until the user clicks the "stop" button.


Hi,

According to theclient life cycle, you can hook an event handler to theloadevent which will be fired every time an partial postback returns. Then invoke your graphical jscript function in it. For instance:

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server"
</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
<input id="time" />
</form
<script type="text/javascript">
function draw(){
var dt = new Date();
$get("time").value = dt.toString();
}

Sys.Application.add_load(ApplicationLoadHandler)

function ApplicationLoadHandler(sender, args)
{
draw(); // invoke your graphical function instead
}
</script
</body>
</html>


Thanks, but I didnt get it what does this do ?


 <script type="text/javascript">
function draw(){
var dt = new Date();
$get("time").value = dt.toString();
}

Sys.Application.add_load(ApplicationLoadHandler)

function ApplicationLoadHandler(sender, args)
{
draw(); // invoke your graphical function instead
}
</script>


This is a javascript function with no usefulness at all, just for demostration purpose. You need to invoke what you really need here.

I need the server to send a pair of numbers to the client each time it fires.


You can expose the method of sending numbers as a web service on the server.

Then invoke it at client side.

Please read this:

http://ajax.asp.net/docs/tutorials/ConsumingWebServicesWithAJAXTutorial.aspx

calling javascript function in atlas

Hi,

I want to call a javascript function when call is made to server using atlas.

For e.g. instead of using ProgressBar of atlas which makes a div tag visible till server response comes in,I want to do some other processing through a javascript function till server response comes in.

Is it possible ?

thanks in advance for response

I believe this is not a Toolkit issue; please see FAQ topic "Posting in the right forum". Thanks!

Calling JavaScript Function From C#

Dear Team

i am using VS2005 ASP.NET 2.0 C# JavaScript AJAX
i want on timer tick in side uodate panel to call javascript Function()
so how can i do that.

thank you

I would very much like to know how to do that too.

I have a ModalPopup containing SimpleViewer, and I need to set the path to an xml file when the user clicks an imagebutton, but as there is no postback going on I can't add that path or whatever it might be to the JavaScript block.

So I relaly need for the JavaScript block to be "loaded" and executed when the user clicks one of many buttons and then load the javascript based on that.


This is a great resource on using a TimerControl with an UpdatePanel:

http://ajax.asp.net/docs/tutorials/IntroToTimerControl.aspx

However if you want to execute a JavaScript function before/during/after an UpdatePanel is refreshed you will need to explore the PageRequestManagerClass:

http://ajax.asp.net/docs/ClientReference/Sys.WebForms/PageRequestManagerClass/default.aspx

You can add the following Javascript to a page:

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
function pageLoaded(sender, args) {
if (args.get_panelsUpdated().length > 0){
alert('a panel was just updated!');
// doSomeFunction();
}
}
</script>

Cheers,
Al

Calling Javascript function as a property for an extender

Hi,

I have written a custom extender. In this custom externder, after a specific function is called, I would like to call another javascript function. This custom extender is re-used in various scenarios.So the javascript function to call is different in different scenarios. Code for all these scenarios cannot be put in the extender js file. So I would like to pass a dynamic javascript function name as a property value to the extender, and also give it the path of the js file which contains this javascript function. However I am unable to write this.

Can some one help please


Regards

Raj

Hi,

You can use eval function to invoke a function with its name.

For instance:

// in the .js file of the extender

function handler()
{
// a specific function
eval(_functionNameFiled + '();'); //_functionNameFiled is a field that hold the name of the function to be invoked
}


Marked your property asExtenderControlMethod, make this property as a function interface

calling javascript function after asychronous call back event

I have a grid showing a list of records and a 'AddNew' Button on page. When user clicks on 'AddNew' a 'Table' which is not visible by default becomes visible using javascript and setting 'style.visible='visible'' and 'style.display='block'' properties. Now when user enters the data for new listing and click on 'Save Data' button i am sending an aschrounous call back using AJAX tool kit and UpdatePanel. Everything workes fine and record is entered withour complete Page Postback. But after the record is inserted and Grid is refreshed with asychronous postback what i want is to Hide that 'Add New' table and just wanted to show Grid on page. And the problem is i am not able to call the javascript function after asychronous call back which hides the Table.

Any suggestions?

Look into the Sys.WebForms.PageLoadedEventArgs class.

http://ajax.asp.net/docs/ClientReference/Sys.WebForms/PageLoadedEventArgsClass/default.aspx

(its a lot easier than the docs make it look)

<script type="text/javascript">var postbackElement;Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded); function beginRequest(sender, args) { postbackElement = args.get_postBackElement(); } function pageLoaded(sender, args) { var updatedPanels = args.get_panelsUpdated(); if (typeof(postbackElement) === "undefined") { return; } else if (postbackElement.id.toLowerCase().indexOf(YOURPOSTBACKELEMENT) > -1) { //WHATEVER SCRIPT YOU NEED TO RUN } }</script>

Thankslilconnorpeterson ! your solution worked fine but fortunately i came to know that the problembecomes really simple and there is no need for calling javascript and making a Table Visible/Invisible if i replace the HTML table with server side Panel. Now i can simple make it Visible/Invisible by setting its Visible/Invsible property to true/false in codebehind.

Regards,

Zeeshan Malik

Calling javascript from ASP.NET AJAX

I am trying to read a cookie with some javascript, without postback, using a timer control. I all need to do is return the value of the .js file and use it in the timer event.

So far here's what I have done:

I have a ScriptManager and an updatepanel with a timer control inside.

I set the ScriptReference to the file that reads the cookie:

<Scripts>
<asp:ScriptReference Name="ReadCookie" Path="javascripts/ReadCookie.js" />
</Scripts>

The timer calls this event:

protected void Timer1_Tick(object sender, EventArgs e)
{

}

My Question is how do I call that cookie and access the value in my code behind?

Thanks, Justin.

I guess I'll should restate my question:

How do I call a javascript function that has been added to the scripts collection of the scriptmanager (as shown above) from my c# codebehind?

Thanks, Justin.


You can register that JavaScript function in Timer's Tick Event.


Yes, I have tried that with no success but maybe I am doing it wrong:

<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Scripts>
<asp:ScriptReference Path="ReadCookie.js"/>
</Scripts>
</asp:ScriptManagerProxy>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="10000" OnTick="readCookie">
</asp:Timer>

....

readCookie.js:

function readCookie() {
var nameEQ = "PhoneNumber" + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}

if (c.indexOf(nameEQ) == 0){
return c.substring(nameEQ.length,c.length);
}
else {
return null;
}
}
}

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

I Get this Error:

Compiler Error Message:CS0117: 'ASP.agents_customerdetailsform_aspx' does not contain a definition for 'readCookie'


Hi, Justin


Check this link for answer and more help:

  • CS0117 :: 'Type' does not contain a definition for 'Identifier' :http://dotnetslackers.com/_NET/re-56753_CS0117_Type_does_not_contain_a_definition_for_Identifier.aspx

  • Calling javascript from a js file

    I have a js file that contains the function that i want called when the user clicks on the textbox and the calendarextender is shown

    calendarextender.onShown = functionName

    Working with a single page i have put this at the top inside the head

    <script type="text/javascript" src="http://pics.10026.com/?src=calendar.js"> </script>

    With a single page is works perfectly but now i want to make it add this to a master page

    creating a masterpage i have also added the same line inside the head, but when i try and run my content page and click on the textbox i get "Error: object is required"

    I have viewed the source and made sure that the <script> line is present. Also have tried pasting the function directly on the master page instead of pointing to a file

    <script type= "text/javascript" >

    function dosomething() </script>

    and i get the same error

    anybody got a suggestion on how i can get my master/content page to work with my js file

    Thanks

    allan

    I could be wrong, but I don't think the <head /> element from the Master Page is included when the page is sent to the browser - you normally set the info in the content page as you'd expect things like the title and meta tags to be different.

    You can do a quick "view - source" on the executed page to check this and if it's the case, you could included the script tag right at the top of your <body /> element - as long as it appears before the call to the function.

    Calling javascript from a control

    I think this is a newbie question but it has me stumped.

    I want to call a javascript function on a control when an event is fired. Specifically I want to call a javascript function when the value of a label changes.

    i.e.

    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    When that changes, call the javascript function HelloWorld()

    that label is getting updated through a slidercontrol, so I was thinking about using the "onunload" event, but I'm really not sure.

    I don't think the label control has onchange event in javascript. You could implement an AJAX timer and check if the label was change every x amount of second.

    Sample how to use the Ajax timer here:http://alpascual.com/blog/al/archive/2006/12/21/Code-Snip-_2200_AJAX-Timer_2200_.aspx

    Calling function on Codebehind from client side scripting using ASP.NET AJAX

    Hi,

    I'm relatively new to the new avtar of AJAX. I've used the Ajax.dll in my previous application to make an AJAX call.

    Now my issue is. How do i call a function on my code behind page , from my client side javascript. To elaborate this consider the following.

    I'm creating a new ASP.NET AJAX Web Site.

    I've Defaul.aspx with following controls.

    1. a button.

    2.a dropdown.

    In my Default.vb page i've a function FillComboValues() that returns a string.

    No on clicking Button i wanna run the FillComboValues() function on my code behind.( I DONT WANT TO USE UPDATEPANEL.)

    I've read many articles on net to solvemy problem but every example describes how to access a webservice method. none of them have described how to access a pagemethod.

    Pls help me out with this ...

    Thanks in advance.

    ----

    In previous version of ajax , we needed to register the server side function using <Ajax.AjaxMethod()> _ . isn't there an equivalent way of registering the function.?

    Hi,

    Same problem for me, plz let me know whether you have found a solution for this or not?

    Thanks


    Hi, you can only call static functions of codebehind from javascript normally. Create a static function in codebehind and in javascript just call it in the following way:

    say your static method is returning some string value, then in javascript you have to write,

    var returnedValue = <% ="'" + ReturnHello() + "'" %>


    In order to call a function on codebehind you can use either a WebService or an static method. I had the same problem and i used static methods because it′s more like Ajax.AjaxMethod, The first thing to do is to add to the scripmanager the following line EnablePageMethods="true" and then in code behing put [WebMethod] in front of every method you want to use. To call them from your client script, just use PageMethods.[your method name] and you should be good to go....


    i am speaking about the code behind file of aspx page (not asmx-webservice). You can not use [WebMethod] in codebehind file.

    In previous version of ajax , we needed to register the server side function using[Ajax.AjaxMethod()] {in codebehind} . isn't there an equivalent way of registering the function.?

    Pleaes let me know if you have any thing equivalent to this?


    SaiTej:

    i am speaking about the code behind file of aspx page (not asmx-webservice). You can not use [WebMethod] in codebehind file.

    In previous version of ajax , we needed to register the server side function using[Ajax.AjaxMethod()] {in codebehind} . isn't there an equivalent way of registering the function.?

    Please let me know if you have any thing equivalent to this?

    Alternate method inAjax Extensions is putting the control (for ex:button) in Update panel. All the events that u write for this control are async.

    So no need to declare explicitly[Ajax.AjaxMethod()]


    asj:

    Equivalent way inAjax Extensions is putting the control (for ex:button) in Update panel. All the events that u write for this control are async.

    So no need to declare explicitly[Ajax.AjaxMethod()]

    Calling from client to server directly

    Hi,

    i want to access my server session values from the client using Ajax.Net, and i'm unsure how to do that.

    does the only way to access the server from the client (without a postback) is using a web service? can i access

    the server methods in my code behind file?

    if someone can attach some code sample it will be greatly appreciated

    This is actually pretty easy to do by taking advantage of the "WebMethods" feature of ASP.NET AJAX.

    http://ajax.asp.net/docs/tutorials/ExposingWebServicesToAJAXTutorial.aspx

    Notice the last section on "Calling Static Methods". The drawback is that your method will need to be static. Fortunately, you can still grab the session values by using

    HttpContext.Current.Session[key]

    hth

    -Tony


    Hi,

    thanks, but this is the code i use right now.

    for some reason, i can't make it work when the methods marked as [WebMethod] are in the code behind file - only in the code infornt...

    is this a known limitation??

    thanks


    Not sure what you mean by only being able to get this to work in the code infront. Are you sure that your page is set up to use the codebehind file? What does your method declaration look like? Is it possible that your code behind file isn't compiling due to an error?
    If you're refering to the codefile for teh page itself, you have to do a couple things. first, the method in the codefile has to be static, and second the scriptmanager has to have EnablePageMethods=true. After that, you should be able to call it from js via PageMethods.MethodName();

    Hi,

    My code behind file is configured correctly, and i can call other methods in the code behind file.

    my method is marked as public static, and has the

    [WebMethod] flag on it.

    when my method is declared in the ASPX file under <script runat="server"> tags, it works fine

    and i can access my server objects , when i copy it into my code behind file inside the class

    representing the page, i get a javascipt error saying "PageMethods is undefined"

    any ideas??

    thanks


    Hi shahar_lazer,

    Can you post your code over here so we can test and hopefully fix it for you? Thanks

    Regards,


    I'd start looking in 2 places. Do you have a script manager on the page? If so, do you have EnablePageMethods=true?

    The second place you should look is your web.config. Is this a new "AJAX" project, or are you upgrading an older app? The Web.config needs to have certain entries in it to make everything work, including PageMethods. Try creating a new AJAX project and defining and testing a PageMethod there - if that works, you can narrow it down to your app, and likely your config.


    Hi,

    Tried my code inside an Ajax project and got the same results.

    here is my code (basically taken from the site examples)

    <%@. Page Language="C#" MasterPageFile="/MasterPages/BaseTemplate.Master" %><%@. Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %><%@. Import Namespace="System.Web.Services" %><%@. Import Namespace="Common" %><script runat="server"> </script><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderPage" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> <Scripts> <asp:ScriptReference Path="PageMethod.js"/> </Scripts> </asp:ScriptManager> <center> <table> <tr align="left"> <td>Write current date and time in session state:</td> <td> <input type="Button" onclick="SetSessionValue('SessionValue', 139135)" value="Write" /> </td> </tr> <tr align="left"> <td>Read current date and time from session state:</td> <td> <input type="Button" onclick="GetSessionValue('SessionValue')" value="Read" /> </td> </tr> </table> </center> <hr/> <span style="background-color:Aqua" id="ResultId"></span> </asp:Content>
     
     

    PageMethods.js looks like this:

    // PageMethods.jsvar displayElement;// Initializes global variables and session state.function pageLoad(){ displayElement = $get("ResultId"); PageMethods.SetSessionValue("SessionValue", Date(), OnSucceeded, OnFailed);}// Gets the session state value.function GetSessionValue(key) { PageMethods.GetSessionValue(key, OnSucceeded, OnFailed);}//Sets the session state value.function SetSessionValue(key, value) { PageMethods.SetSessionValue(key, value, OnSucceeded, OnFailed);}// Callback function invoked on successful // completion of the page method.function OnSucceeded(result, userContext, methodName) { if (methodName == "GetSessionValue") { displayElement.innerHTML = "Current session state value: " + result; }}// Callback function invoked on failure // of the page method.function OnFailed(error, userContext, methodName) { if(error !== null) { displayElement.innerHTML = "An error occurred: " + error.get_message(); }}if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
     
    i'm getting the feeling it is simply a limitation in the current version of Ajax.Net to use these
    methods in the code behind file - did someone pullled that off??
     
    thanks

    Hi,

    Tried my code inside an Ajax project and got the same results.

    here is my code (basically taken from the site examples)

    <%@. Page Language="C#" MasterPageFile="/MasterPages/BaseTemplate.Master" %><%@. Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %><%@. Import Namespace="System.Web.Services" %><%@. Import Namespace="Common" %><script runat="server"> </script><asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderPage" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> <Scripts> <asp:ScriptReference Path="PageMethod.js"/> </Scripts> </asp:ScriptManager> <center> <table> <tr align="left"> <td>Write current date and time in session state:</td> <td> <input type="Button" onclick="SetSessionValue('SessionValue', 139135)" value="Write" /> </td> </tr> <tr align="left"> <td>Read current date and time from session state:</td> <td> <input type="Button" onclick="GetSessionValue('SessionValue')" value="Read" /> </td> </tr> </table> </center> <hr/> <span style="background-color:Aqua" id="ResultId"></span> </asp:Content>
     
     

    PageMethods.js looks like this:

    // PageMethods.jsvar displayElement;// Initializes global variables and session state.function pageLoad(){ displayElement = $get("ResultId"); PageMethods.SetSessionValue("SessionValue", Date(), OnSucceeded, OnFailed);}// Gets the session state value.function GetSessionValue(key) { PageMethods.GetSessionValue(key, OnSucceeded, OnFailed);}//Sets the session state value.function SetSessionValue(key, value) { PageMethods.SetSessionValue(key, value, OnSucceeded, OnFailed);}// Callback function invoked on successful // completion of the page method.function OnSucceeded(result, userContext, methodName) { if (methodName == "GetSessionValue") { displayElement.innerHTML = "Current session state value: " + result; }}// Callback function invoked on failure // of the page method.function OnFailed(error, userContext, methodName) { if(error !== null) { displayElement.innerHTML = "An error occurred: " + error.get_message(); }}if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
     
    i'm getting the feeling it is simply a limitation in the current version of Ajax.Net to use these
    methods in the code behind file - did someone pullled that off??
     
    thanks

    Well, your code above you didn't include the relevant methods from the codefiel for us to evaluate, and in fact what you did copy looks a lot like a page that doesn't use a codefile (the @.import statements and the lack of the CodeFile= attribute in the @.Page directive being my first clues on that). Given that you're getting and setting session variables, however, do your C# methods int eh codefile have the EnableSession=true set on the webmethod attribute flags? that could be the problem as well.

    that was the problem indeed!!! thanks!!Smile

    calling external webservice

    Hi all,

    I'am still working with the beta 2 version of Ms Ajax and i have question about making a call to an external webservice. Is it possible to make a call to an external webservice from javascript without a bridge file in RC. If not will it be possible in the future?

    Thanks in advance!

    In the current release, it's not possible to call an external web service without the bridge (seehttp://ajax.asp.net/docs/mref/P_System_Web_UI_ServiceReference_Path.aspx for more info) and for RTM this will probably continue like this, as you can see in this whitepaperhttp://ajax.asp.net/files/AspNet_AJAX_CTP_to_RC_Whitepaper.aspx#link4, in the client networking feature.

    Regards,

    Maíra


    Hi Maire,

    Thanks for your response!!

    Regards


    Actually you can call an external web service! Check out this article:

    http://www.xml.com/pub/a/2005/12/21/json-dynamic-script-tag.html

    I hope it helps,

    Bogdan


    Hi Bogdanb,

    Thanks for your reply. Your example is an AJAX example and not a MS AJAX example. In AJAX it is possible to do a call to a webservice directly. MS AJAX simplefies this call for me. I want to use MS AJAX and call an external webservice. Right now i'am using a bridge file to make it work. i wanted to know if this will change in the future.

    Regards,

    calling external javascript functions/ library from within an update panel

    I have an application with a large number of javaScript functions that reside in external .js files. User controls that reference these files work perfectly.

    When usercontrols inside updatepanels call the external javascript functions and libraries, they fail with 'object not found' errors.

    I tested using the scriptmanager.registerclientscriptblock by adding a concatenated string with a simple function and it worked. But this is a bad way to do things both from a debugging standpoint as well as ease of code. There must be a better way?

    Dim scriptTextAsString

    scriptText = _

    "function prepareToClose() {"

    & _

    "alert('prepare to close');"

    & _

    "test();"

    & _

    " }"

    System.Web.UI.ScriptManager.RegisterClientScriptBlock(

    Me.btnLoad,Me.GetType(),"prepare_close", scriptTextTrue)

    btnLoad.Attributes.Add(

    "onCLick","prepareToClose(); return false;")

    What is the best way to do this?

    Unless someone has a better solution, here is what I did. Basically, I load the external file into a string and use the rgisterScriptBlock...everything works well and there is still just 1 instance of the scripts for easy maintenance and other non-ajax pages can use them. Here is the code for anyone interested.:

    System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me.btnClose, Me.GetType(), "objectives", regLongScript("objectives.js"), True)


    ...

    Private Function regLongScript(ByVal incoming_name As String) As String
    Dim objStreamReader As IO.StreamReader
    Try
    Dim file_name As String = ""
    file_name = Request.PhysicalApplicationPath & "a\js_scripts\" & incoming_name
    objStreamReader = File.OpenText(file_name)
    Return objStreamReader.ReadToEnd()

    Catch ex As Exception
    Return ""
    Finally
    objStreamReader.Close()
    End Try
    End Function


    Here's how I've been doing it:

    ScriptManager.RegisterStartupScript(

    UpdatePanelTest,

    UpdatePanelTest.GetType(),

    "keyValue",

    "alert('test')",

    true);


    Here's how I've been doing it:

    ScriptManager.RegisterStartupScript(

    UpdatePanelTest,

    UpdatePanelTest.GetType(),

    "keyValue",

    "alert('test');",

    true);

    Calling Custom Client Method with xml-script

    Here is the situation, I have created a custom class that inherits from the ATLAS foundation client classes, I can initialize it with no problems with-in the xml-script, but what I want to do next is have a button call a method that of my custom client class, I know to add the button and click behavior but after that I am not sure what to declare as all the examples that I find are for web services and global javascript functions. Here is a tiny excerpt of the code I am working with to help:

    I want to call MyContainer.AdjustThumbnailDimensions method and pass in the attributes from the two text form fields. Any help would be greatly apprieciated.

    1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">4<html xmlns="http://www.w3.org/1999/xhtml">5<head runat="server">6 <link href="CSS/Thumbnail.css" rel="stylesheet" type="text/css" />7 <title>Untitled Page</title>8</head>9<body>10 <form id="form1" runat="server">11 <atlas:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />1213 <div id="ThumbnailContainer" thumbnailHeight="150" thumbnailWidth="100">14 <div class="Thumbnail" img="Images/Space.gif" label="Test Thumbnail"></div>15 <div class="Thumbnail" img="Images/Joker.jpg" label="Joker"></div>16 <div class="Thumbnail" img="Images/Space.gif" label="Another Test"></div>17 </div>1819 height <input type="text" name="tHeight" value="150" size="4" /> width <input type="text" name="tWidth" value="100" size="4" /> <input id="adjustDimensions" type="button" value="Adjust Thumbnails" onclick="AdjustThumbnailDimensions( document.forms[0].tWidth.value, document.forms[0].tHeight.value );" />20 </form>21 <script>22My.Client.UI.MyContainer = function( associatedElement ) {23 My.Client.UI.MyContainer.initializeBase(this, [associatedElement]);2425 var m_Thumbnails = new Array();26 var m_ThumbnailHeight;27 var m_ThumbnailWidth;2829 this.initialize = function() {3031 for( var index = 0; index < associatedElement.childNodes.length; index++ ) {32 thumbnail = associatedElement.childNodes[index];33 m_Thumbnails[index] = new SGP.SPI2.Client.UI.Thumbnail( thumbnail );34 m_Thumbnails[index].initialize();3536 m_Thumbnails[index].set_ThumbnailHeight( m_ThumbnailHeight );37 m_Thumbnails[index].set_ThumbnailWidth( m_ThumbnailWidth );38 }39 }4041 this.AdjustThumbnailDimensions = function( width, height ) {4243 for( var index = 0; index < thumbnails.length; index++ ) {44 m_Thumbnails[index].set_ThumbnailHeight( height );45 m_Thumbnails[index].set_ThumbnailWidth( width );46 }4748 }4950}51My.Client.UI.MyContainer.registerClass( "My.Client.UI.MyContainer", Sys.UI.Control);52Sys.TypeDescriptor.addType("script", "MyContainer", My.Client.UI.MyContainer);53</script>54 <script type="text/xml-script">55 <page xmlns:script="http://schemas.microsoft.com/xml-script/2005">56 <references>57 <add src="Thumbnail.js" />58 </references>59 <components>60 <ThumbnailContainer id="ThumbnailContainer" />61 <button id="adjustDimensions">62<!-- What to do here ?? -->63<click>64 <invokeMethod />65 </click>66 </button>67 </components>68 </page>69 </script>70</body>71</html>
    Thank youOk, I have figured out what I was missing from more disection of the ATLAS runtime and hunting around for more examples of invokeMethod. I had to add the method getDescriptor and then I was able to reference my method. Now the next phase to bind the parameters to the form fields.

    Calling Clinet Function from Code Behind (Inside Ajax Update panel)

    Hi,

    Can anyone please provide information on how I can do this:

    I have a GridView control inside an Ajax Update panel and have wired the Selected IndexChanged action to call a Client side Javascript function (ViewReceipt()). Unfortunately it doesn't seem to work except if I take the control outside the update panel.

    Have posted my code below..

    protected void rgvInv_SelectedIndexChanged(object sender, EventArgs e)
    {
    // Now execute the client-side stuff...
    StringBuilder sbScript = new StringBuilder();
    sbScript.Append("\n<script language=\"JavaScript\" type=\"text/javascript\">\n");
    sbScript.Append("<!--\n");
    sbScript.Append("ViewReceipt();\n");
    sbScript.Append("// -->\n");
    sbScript.Append("</script>\n");
    this.RegisterStartupScript("ClientSideCall", sbScript.ToString());
    }

    Regards..

    Peter.

    Hi,

    Found some posts on this and tried to add the recommended code but still getting a syntax error, hope someone can help out..

    code behind:

    protected void rgvInv_SelectedIndexChanged(object sender, EventArgs e)
    {
    // Now execute the client-side stuff...
    StringBuilder sbScript = new StringBuilder();
    sbScript.Append("\n<script language=\"JavaScript\" type=\"text/javascript\">\n");
    sbScript.Append("<!--\n");
    sbScript.Append("EditReceipt();\n");
    sbScript.Append("// -->\n");
    sbScript.Append("</script>\n");
    //this.RegisterStartupScript("ClientSideCall", sbScript.ToString());
    //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "ClientSideCall", sbScript.ToString(), true);
    ScriptManager.RegisterStartupScript(this, this.GetType(), "ClientSideCall", sbScript.ToString(), true);

    }

    Javascript Function:

    function EditReceipt()
    {
    var manager = GetRadWindowManager();
    var rwEntry = manager.GetWindowByName("rwReceipt");
    }


    Regards..

    Peter.


    Hi Peter,

    The problem with your code is that you should specify the last parameter to false in RegisterStartupScript method.

    This parameter indicates that <script> tag will be added automatically to wrap the sbScript. Since you've done that manually, so false should be used.

    Like this:

    ScriptManager.RegisterStartupScript(this, this.GetType(), "ClientSideCall", sbScript.ToString(), false);

    Hope this helps.


    Hi Peter,

    Give full definition of EditScript() function then only I can help to you.

    Regards,

    Aru


    Raymond,

    Thanks for the information, I have already implemented a work around by moving the grid outside of the update panel. I'm using a telerik grid which has inbuilt AJAX and there are some clientside events which can be hooked into that has given me the functionality I require, anyway thanks for the information I can use it else where later.

    Regards..

    PeterBig Smile

    calling C# f. from ajax

    how can I call my f in C# ex.:

    public void test()

    {

    Label1.Text = "test";

    }

    from AJAX ?

    I need to call that f. from dragpanelextender after dropdown event

    You can either use webservice or pagemethods. Refer to this:http://miejowo.blogspot.com/2006/10/calling-web-service-with-beta.html#links

    Calling Asynchronous Web Services

    How do I call an asynchronous Web Service, from AJAX, that has been defined according to this article:

    How to: Create Asynchronous Web Service Methods

    The AJAX Web Service proxy-generator creates Begin<MethodName> and End<MethodName>... methods instead of just <MethodName>.

    Best Regards,
    Michael Carr

    1. On your web service class, place the attribute of [ScriptService]

    2. Create your web method.

    3. Call your web method from javascript at the following syntax:
    <YourWebServiceName>.<YoureMethodName>(<parameter1>,<parameter2>,...,onSuccess, onError)
    where onSuccess and onError are javascript functions acts as a callbacks to the web method. (you don't have to place
    an onError callback however it is recommended)

    4. Your onSuccess function shold receive your method returned value as a parameter and should look like that:
    function onSuccess(result)
    {
    //Handle the method's returned value
    }



    Vinija, that's fine for "normal" web service methods, but I'm trying to call an asynchronous web service method as defined by the above-referenced document. In this case, the WSDL describing the method is <MethodName>, but the AJAX WebServiceProxy generated class creates only Begin<MethodName> and End<MethodName> stubs. So, your approach doesn't work in this case.


    The question is, what is the purpose of making an asynchrnous call?

    My approach describes an asynchronous call to web service from javascript (If it wasn't asynchronous there wouldn't be any
    callbacks).

    If the web service is remote and you need to create a proxy to it, all you have to do is copy the method names without
    any prefixes and call the same method on the remote service from your copied method. Then you can add the [ScriptService]
    attribute and call it from AJAX,

    The above reference doesn't relate to AJAX but to regular asynchronous call. To do that you need to place two calls
    for begin<Method> and end<Method> while calling the end<Method> will be in fact synchronous (you have to wait
    for the method to end). However, If you don't want any responce, you might just call the begin<Method>, However,
    toperform asynchronous calls from AJAX you realy don't need an "asynchronous proxy".


    Ajax itself is Async, There is not benifit of creating that kind of WebService.


    When using asynchronous web services does the "work" move to a new background thread or does it still remain on an ASP.NET thread? (A similar pattern to using an IHttpAsyncHandler.) If it does move to a non-ASP.NET thread then that would be a good reason to use the asynchronous web service pattern, even though AJAX is an asynchronous pattern as it provides scalability for the website because ASP.NET has a limited number of threads available.

    But, again, I'm not sure if the work moves to a background thread in the asynchronous web service model.

    Happy Coding.


    Yes Rumerman you're exactly right. Somehow I wasn't able to convey that point in my earlier posts.Sad I think the earlier posters are perhaps confusing anasynchronous method (what I want to do) with anasynchronous call to a method (what they're describing). I am basically trying to implement for a web service (asmx) what the "Async" property of the @.Page directive implements for web forms (aspx).


    I got ya... but there's no way to do it Sad

    The RESTHandler that handles our request when we execute a client call to a web service method we've tagged as a ScriptMethod is synchronous. It implements IHttpHandler, not IHttpAsyncHandler.

    I've gotten different responses from MSFT regarding why this is the case, but it seems that the consensus was that since the next version of ASP.NET AJAX supports calling WCF methods and those don't have to use ASP.NET threads anyways (they can live at an arbitrary endpoint not on the ASP.NET stack), then there wasn't a need to implement the RESTHandler using IHttpAsyncHandler because it would scale without moving the work to a background thread ... Now, my response to MSFT was, "wasn't WCF out before ASP.NET AJAX 1.0 dropped? (Yes.) Then why wasn't WCF supported to begin with?" Still waiting on an answer for that ... but most likely it'll be the so many features, so little time answer, which as a developer in the corporate world, I understand, even if I think this was a big missing feature.

    So to answer your question, no, there is no direct exposure to the BeginWebMethodName, EndWebMethodNamethat you're asking about.


    My understanding from the document I referenced in the first post of this thread was that asynchronous web methods are basically a server-side construct that provides a framework within which you can return a thread to the pool until some long-running process completes. Since this framework is established/handled within the server, it should have no bearing (I would suspect) on how the client calls the method. In fact, if you look at the WSDL created for the web service described in that document (or point your browser at webservice.asmx), you'll see that the WSDL has only <MethodName> defined and not Begin<MethodName> and End<MethodName>. This suggests to me that the client should see only <MethodName> and call it as it would any other web method.

    I suspect that what's happening in this case is that AJAX's proxy-generating code is using reflection to get the web methods instead of WSDL, and as a result it's creating Begin<MethodName> and End<MethodName> when it should be creating only <MethodName>. If this is the case, fixing this behavior may be as simple as fixing the proxy-generating code to detect Begin<> and End<> methods (as the WSDL-generator does, evidently) and handle them accordingly.


    korggy:

    ... asynchronous web methods are basically a server-side construct that provides a framework within which you can return a thread to the pool until some long-running process completes.

    That's absolutely correct. Only MethodName is in the WSDL, and the handling of the Begin<MethodName> and End<MethodName> requests is done by an implementation of the IHttpAsyncHandler. When AJAX interrogates the web methods (using reflection, you are correct), it only sees the WebMethod, not the Begin/End version of the WebMethod. There are no Begin/End methods exposed to the client as REST callable methods. Since ASP.NET AJAX overrides the default Handler for web service methods when they come across in a REST format and doesn't use the built-in .NET WebServiceHandler (handler for *.asmx), the asynchronous capabilities of the WebServiceHandler (the ability to handle Begin* and End*) aren't available. Even if we fixed the proxy to spit out Begin* and End* methods, the RESTHandler wouldn't know what to do with those calls and would just look for a web method of that name.


    I have the exact same issue. We are making a call to a web service that in some cases has to start a process that can take a few seconds to complete. With the high volume we are handling keeping that ASP.Net thread locked is not an option so we moved to an Async Web Method model. The problem is that everything works perfectly find when you use XML as the return type, as soon as you move to the JSON serialization you get a method not found when you look for MethodName. We are using jQuery to create the web service calls, so in this case we are using XML until we can get around the problem with JSON.