Showing posts with label call. Show all posts
Showing posts with label call. Show all posts

Wednesday, March 28, 2012

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 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 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 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 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.

Calling ASP.NET event handler from Javascript

Does anyone know how to call an event handler from Javascript? What I am trying to do is a user clicks a button, I check to see that all the tasks are complete (from the database), if they aren't I display a confirm box saying "Should we mark all the tasks as complete?" If they select yes, I want to call a function in the ASP.NET code.

Any suggestions would be much appreciated!

Thanks,
Matt

In asp.net 1.0 and 1.1 it was

__doPostBack('myButtonID', '');

You may have to a validator on the page so that asp.net renders the javascript to handle this. You can easily put a linkbutton on with the url set to empty (or something like this).

EDIT : It gets complicated if you need the button to also do some validation. Let me know and I can try to help here.

There is a better method in asp.net 2.0 - something on a button called onBeforePostBack(). Not sure as I do not use it.


I have determined a solution to this problem. I create the "confirm" message on the server side:

string scriptCode ="if(confirm('Not all work order items have been marked as done. Would you like to mark all items as done and close the work order anyway?') == true) confirmComplete();";

as you can see, I place the confirm in an if statement that calls a javascript function on the page. The javascript function just calls the "click" event on a button I have place on the page and hidden using CSS. The action that the button takes on the server side is the action want it to take.

This brings an interesting problem. When I use the javascript function to click the button, it posts back but does not update the screen. Any suggestions now?

-Matt


Check this link

http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx

Calling AJAX function

Hi, I wonder if there's a way to call an AJAX function via code behind page. That is, I have an asp tab control on my page, in which on pressing a tab I open a menu via AJAX code and ask user to enter password then I validate that password and want to select that tab if password is correct. Since my tab is asp control the AJAX code doesn't know that so I have to return the password to the code behind page but since I have to call such function through AJAX:

[Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public void CheckRoomPsw(string psw)
{

...

}

I don't have access to Tab control because this returns null, so there's two options which I don't know how to perform:

1. call an AJAX control from CheckRoomPsw(string psw)

2. get an access to tab control in CheckRoomPsw(string psw)

Any idea is appreciated.

have you tried using the findControl function. it lets you access a conrol by referencing its location and using its ID. so if you had a bunch of controls on your form and wanted to get to one you could do.

form1.findControl("controlIDgoesHere");

if yours is inside of some ajax stuff it might be like

UpdatePanel1.findControl("myControlsID");

then you can just cast that to reference the object type

string value = ((TextBox)form1.findControl("txtUserName")).Text;


Actually, I've done that:

[Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public void CheckRoomPsw(string psw)
{
JQD.TabStrip ts = (JQD.TabStrip)this.FindControl("TabStrip1");
ts.SelectTab(Global.tabPos);
}

but this returns null!!

I think it's because CheckRoomPsw() is an AJAX function


Perform the tab selection on the client-side callback. Return a boolean from the AJAX method after you check the password, if it is true perform the tab selection.


Also, it looks like you're using AJAX.NET, which is a completely separate product from ASP.NET AJAX, so you might want to see if they have a forum.


Have you had luck fixing your issue?

-Damien


Not yet!

I'm still looking for solution!


Have you tried doing the tab selection client-side?


I tried much to get access to the tab control from js code (client side) but since the tab control is an asp user control, it can't be known from js code.


Use theOnClientActiveTabChangedproperty on the tab. Seehttp://asp.net/AJAX/Control-Toolkit/Live/Tabs/Tabs.aspx for more information.

-Damien


Thanks for your concern Domien!

However, I'm not using AJAX.net and don't know much about itEmbarrassed and it's a bit risky to change my tab control now that I'm on the final steps of completing my project

IS there any other solution please

Calling a Webservice from within a javascript object - closure issue?

Hi,

I'm making a client side call to a web services but I need to wrap up the functionality that makes the call within another object. The code is below. The code worked fine before I wrapped it in the "ImageViewer" object but now when I try to call the Web Service Method it doesn't recognise the onComplete call back function and says "onComplete" undefined. (See the getImageIDs method). I suspect this is something to do with scope and/or closure but I've been unable to come up with a solution. What is the correct way to do this? Any help will be appreciated.

Type.registerNamespace(

"Raydius");

Raydius.ImageViewer =

function(ImageDivID, ImageListDivID){this.ImageDiv = $get(ImageDivID);this.ImageListDiv = $get(ImageListDivID);this.ImageIDs = [];this.Images = [];

}

Raydius.ImageViewer.prototype = {

getImageIDs:function(id){

// Call the WebService

RaydiusWS(id, onComplete);

},

onComplete:

function(results){

alert(results);

},

onTimeOut:

function(results){

alert(

"Timeout");

},

onError:

function(results){

alert(

"Error");

}

}

Raydius.ImageViewer.registerClass(

'Raydius.ImageViewer');function initImageViewer(){

var viewer =new Raydius.ImageViewer("ImageDiv","ImageListDiv");

viewer.getImageIDs(1);

}

See if my example here helps you:

http://forums.asp.net/thread/1574034.aspx


Thanks for the response. There was actually a daft error in my code that was stoppinmg it working both the other post you directed me to was helpful. The userContext param is very useful.

Thanks

Mat

Calling a Web Service from within JavaScript source

I'm trying to make an internal Web Service call from within an ATLAS client control, but I can't figure out how to get the parameters passed into the call properly into the Invoke method for ServiceMethod.

The following manages to call the Web Service but the parameter is not respected.

var num =new Object();

num.Value = -1;

var serviceMethod =new Sys.Net.ServiceMethod(_serviceURL, _serviceMethod,null/*? _appUrl */);var _request = serviceMethod.invoke(num, _onMethodComplete, _onError,

_onError,_onError,

this,

2000, Sys.Net.WebRequestPriority.Normal);

Actually I can see that the object needs to be formatted with the name of the parameter. While I can do this for testing - at runtime I have no idea what service the user is connecting to so I won't know the name of the parameter. Isn't there some more generic way to call the Web Service from code?

Also what is AppUrl in this context?

I suspect the answer is the higher level ServiceMethodRequest, but it takes a UserContext object that I have no idea how to create.

Any ideas appreciated.

+++ Rick --

The first parameter to invoke() is an object that wraps all the parameters of your server method. e.g if your server method takes an int named 'n' and a string named 's', you would have:

serviceMethod.invoke({i:5, s:"Hello"), ...)

David


Ok, that's not terribly useful <g>... All of the values passed are going to be variables. Unless I parse this myself I can't see how to call the service dynamically with this scheme.

There's gotta be a higher level mechanism for making a remote Web Service call? If not, then that's something that should maybe be there? Similar to what Callmethod used to do?

+++ Rick --


Not sure I'm following you. In the code above, you can replace 5 and "Hello" by arbitrary variables.

Note that there is indeed an alternative way of calling services by using the generated proxy. See thispage for an example.


Yeah of course I can call a Web Service that's PREDEFINED using the proxy class generated, but that doesn't help if you need to call the service when you don't know beforehand what the name is or what's exposed on it. If you want dynamic execution you won't know immediately at runtime what the parameters are or what the type.

So yeah, I can write a string value there but if I don't know that it's a string beforehand it gets to be a major hassle to write that call.

Consider this scenario: You build a custom client control and you have an option to call a service Url with arbitrary parameters that are set up in an array. Then you have to parse that call into this funky syntax.

There needs to be a way to dynamically call a service the same way that CallMethod used to work.


Yeah of course I can call a Web Service that's PREDEFINED using the proxy class generated, but that doesn't help if you need to call the service when you don't know beforehand what the name is or what's exposed on it. If you want dynamic execution you won't know immediately at runtime what the parameters are or what the type.

So yeah, I can write a string value there but if I don't know that it's a string beforehand it gets to be a major hassle to write that call.

Consider this scenario: You build a custom client control and you have an option to call a service Url with arbitrary parameters that are set up in an array. Then you have to parse that call into this funky syntax.It doesn't work.

There needs to be a way to dynamically call a service the same way CallMethod used to work. So you can specify an array of values, an endpoint Url and method name.


I do not think Macrh CTP directly provides the functionality you are looking for. But if you can exam how Sys.Data.DataSource class works. it may provide some hints if you decide to write you own class to accomplish your goal.

Actually, the syntax above is completely generic, and requires no hard coded knowledge of any aspect of the web service. All the parameters are passed as arbitrary name/value pairs on a standard Javascript object, which can be added dynamically.

David


David, I think your sample code is some kind of generic, but i don't see how it works if we don't know , at design time, what public web services out there user want to call.


Why do you think you need to have this information at design time? Every piece of the code (the URL, the method name, the parameter names and values) can be specified dynamically.

Of course, if you are referring to the proxy class, then yes, that is only usable for the case where you know at design time what service you want to call. But the original post was not about the proxy.

David


Hi David,

We seem to have some sort of disconnect here. Let me explain what I mean.

You said:

The first parameter to invoke() is an object that wraps all the parameters of your server method. e.g if your server method takes an int named 'n' and a string named 's', you would have:

serviceMethod.invoke({i:5, s:"Hello"), ...)

First is that type prefix required or not? I think I tried without it and it didn't seem to work. If it is required then the above is not generic because you'd have to parse the values into the above format and then eval it into a string somehow which is a mess.

You say the above with such certainty, but you have to remember we're working off this stuff blind. This stuff isn't documented. We DON'T KNOW what the parameter signature is, we have to guess...

So anything you can do to explain would be really helpful...

Thanks,

+++ Rick --


Hi Rick,

In Javascript writing { i:5, s:"hello" } creates an object that contains two fields with those name/value pairs. 'i' and 's' are not prefixes, they are field names, and in Atlas JSON services (as in SOAP) they are required since parameters are passed by name (and not by order).

Another way to create this same object is to write:

var o = {};
o.i = 5;
o.s = "hello";

And yet another way which I think will be the one you want is:

var o = {};
o["i"] = 5;
o["s"] = "hello";

Note that that there is no need to call eval(), which would indeed be ugly (and inefficient). Does that give you what you are lookin for?

And I certainly realize the doc is poor and samples are limited. But they'll get better! :)

David

Calling a web service from javascript at page load

I need to call a web service at page load from javascript. I have several other web services that are successfully called on other occasions (when leaving a text input field for example).

I suspect the reference by the script manager to the services aren't done at the moment of the call (when the page load). The service is working fine when called from another "event handler" i.e. whenever input events are fired. Also, any service I try to call at page load failed to be called.

So, do I guess right? What can I do to get my call to work?

I'm using April CTP

Thank you all in advance

Check thishttp://atlas.asp.net/docs/atlas/doc/services/exposing.aspx

look for Calling Web Services When a Page Loads, hope this helps.


Thank you very much... I should have look twice in the documentation

The documentation doesn't exist anymore, and the trick it suggested no longer works on Beta 2:

<scripttype="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
<references>
</references>
<components>
<application id="application" load="OnApplicationLoad" />
</components>
</page>
</script>

What's an alternative way to do this besides using setTimeout to wait some arbitrary number of seconds before calling that javascript function "OnApplicationLoad"?

Calling a WCF secure service

I know Atlas has some extensions to call WCF services but I am wondering is there any way to call a service using WS-Security instead of transport security (Https) ?.

Thanks

Pablo.

Hi Pablo,

Atlas is targeted on the "reach" end of the spectrum, which means it's pitched at technologies that are already widely deployed today. This necessarily means it can't take advantage of some of the richer protocol work like WS-Security because it's new and not everyone understands how to speak that stuff yet. I think of that as the "reach/rich tradeoff". The unfortunate reality is that you can't optimize for both at the same time.

However, history has shown that technologies that were once squarely in the 'rich' end of the spectrum have a tendency to become ubiquitous over time (a great example of this is DHTML, which has been around for years but has only recently become interesting).

Interesting times ahead :)
-steve
Thanks a lot Steve!!!. I just want to be sure about that.

calling a VB class from Javascript?

Hi, I created a webservice to return a dataset for my autocomplete word list. Now, I am wondering if it's possible that we could call a vb class in javascript function? Eg.

HTML:<inputtype="text"onkeypress="return getList(this);"id="strSearch"/>

Javascript: function getList(word) { // call or invoke vb class to return dataset }

If that is impossible, is there anyway to create a autocomplete WITHOUT using XMLHTTP ..?

Take a look at pagemethods with the script manager.


I think you can use Async Postback. Take a look athttp://forums.asp.net/t/1168088.aspx

Let me know if it answers your question.

Thanks


Unless you remote script it in an iframe, whatever you do with AJAX is going to use XmlHttpRequest. Why do you want to avoid that?

Page methods might work well for what you're doing, though you'd need to convert your DataSet to an array before returning it. The AJAX framework doesn't support serializing DataSets to JSON quite yet (soon).

However, if all you want is an auto completing TextBox, you should just take a look at theAutoComplete extender in the AJAX Toolkit. No point in re-inventing the wheel.


No, JavaScript can not call a function that is serverside code. It can only call JavaScript code. If you want to call code on the server, you should ook into using the pagemethod,http://forums.asp.net/t/1175553.aspx:

For more infomation, seehttp://www.asp.net/ajax/documentation/live/tutorials/ExposingWebServicesToAJAXTutorial.aspx, especially the following section:

Calling Static Methods in an ASP.NET Web Page

You can add static page methods to an ASP.NET page and qualify them as Web methods. You can then call these methods from script as if they were part of a Web service, but without creating a separate .asmx file. To create Web methods in a page, import theSystem.Web.Services namespace and add aWebMethodAttribute attribute to each static method that you want to expose.

To be able to call static page methods as Web methods, you must set theEnablePageMethods attribute of theScriptManager control totrue.

The following example shows how to call static page methods from the client script to write and read session-state values.

RunView

Best Regards,

Calling a simple JS Function in the "Atlas way"

How could I, from an server-side control (like a Button), call an JS Function?
In the "old way", I used theRegisterClientSideScriptBlock to do this, but it does not work in the Atlas.

Thanks in Advance for the attention,
Fract4L

RegisterClientSideScriptBlock isn't working anymore for you with Atlas? Could you post a code sample showing the problem and describe what error you're getting if any?


I haven't tested this with Atlas but I assume it should work. This might even be some deprecated method of calling a JS funcion from a .NET control but I would always add the following to the page_load.

Button1.Attributes.Add("OnClick", "HelloWorld();")

Not sure again if this will work in Atlas, but it does add the js event function to the button itself.

JoeWeb


hello.

use the overload that has a boolean as its last parameter. this method will generate the correct script block in all cases (i think that you're script string has <script type='javascriopt'> on it, right? if you fo this, it won't work in atlas because only the scripts that have the type attribute set to text/javascript will be correctly loaded by the platform).

regarding the bt click handling on the client side, you can also use the new onclientclick property intesad of using the attributes collection.


Hello all,

TheRegisterClientScriptBlock was deprecated in favor of the classClientScript, that has all the funcionallities of the old method and some new ones.


Either way, thanks in advance for your fast responses and I hope that this question could help others.

Fract4L

Here is the code:

1protected void btnAccess_Click(object sender, EventArgs e)2{3// this works fine ;-)4StringBuilder sb =new StringBuilder();5sb.Append("<script type=\"text/javascript\">");6sb.Append("alert('test');");7sb.Append("</" +"script>");8ClientScript.RegisterClientScriptBlock(this.GetType(),"test", sb.ToString());9}

hello.

i'd remove the lines <script> and </script> and add ,true to the registerclientscriptblock method.