Showing posts with label client. Show all posts
Showing posts with label client. Show all posts

Wednesday, March 28, 2012

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 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 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 An UpdatePanel Update from Javascript

From client side javascript I want to invoke an UpdatePanel's Update event. I do not see any documentation on a method to do this. I found triggers but those are based upon controls, I want to do this purely via javascript.

I wonder if
the internal method Sys.WebForms.PageRequestManager _updatePanel Method does the job.

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 server side function from client side using the toolkit

Ok, I'm sure this is a really stupid question, but I'm willing to ask it anyway.

Let's say that I created a new extender called "My", so I now have three files files, MyExtender.cs, MyBehaviour.js, and MyDesigner.cs.

I want my control to be able to take some data on the client side and use it to retrieve some data on the server side, which AJAX is all about right? :) So for the sake of argument, let's say I want to enter an email address in a textbox, and then consult a database to return the user's password.

So in my MyExtender.cs file, I create a function something like this:

public string getPassword(string email) {

... Make some database calls to get the info

return password;

}

What code do I put into the MyBehaviour.js file in to to call the getPassword function? And do I need any special decorations on the getPassword() function to make it happen?

You can use ICallbackEventHandler interface for this purpose. This is the exact purpose of this interface in ASP.Net 2.0. Check out the MSDN for this interface.


You really should look at how to create an extender to do it the best way. There is a great tutorial here,http://www.asp.net/ajax/ajaxcontroltoolkit/samples/Walkthrough/CreatingNewExtender.aspx that is a simple example of how to create a simple extender. Also if you just want to use the code behind to retrieve info from the database, you may just want to wrap an update panel around your form and get the data from the code behind. Either way you will be able to accomplish what you want.

Monday, March 26, 2012

Calling __doPostBack causing full postback :-(

Ok, if I capture an event on the client, for example, a click event on a textbox that is inside an update panel, and in that event I call __doPostBack I get a full postback.

However, if I add a button and call it's click event, I get the partial page update I want. So I guess the question is how to invoke a partial page update via script?

Thanks ... Ed

Make sure the appropriate trigger has been set up for the UpdatePanel. You can also set the TextBox to have AutoPostBack="true" which will add a __doPostBack to the onchange event handler.

Of course if you absolutely need to trigger a button click from JavaScript you can do something similar to this:

<

htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>Untitled Page</title>
<scriptlanguage=javascript>
function SemiHacky(){
__doPostBack('Button1','');
}
</script>
</head>
<body>
<formid="form1"runat="server">
<asp:ScriptManagerID="ScriptManager1"runat="server">
</asp:ScriptManager>
<asp:UpdatePanelID="UpdatePanel1"runat="server">
<Triggers><asp:AsyncPostBackTriggerControlID=Button1EventName="Click"/></Triggers>
<ContentTemplate>
<asp:LabelID="Label1"runat="server"Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:ButtonID="Button1"runat="server"Text="Button"/>
<br/><br/>
<ahref="javascript:SemiHacky();">Click here</a> to execute some JavaScript and submit the Button1 button via JavaScript.
</form>
</body>
</html>

The code behind is just setting the Label text to the current time so you can see the PostBack occur:

Label1.Text =DateTime.Now.ToString();

Cheers,
Al


Hi,

I did exactly as you suggested, but to no avail.

I am trying to launch a modal dialog and I have tried the following variations, some of which seem to work correctly, except that once the modal dialog is display and I try to dismiss it via a server

side mydlg.close() I get an error stating "The control 'dlgDivTasks' already has a data item registered."

These are the individual calls that I have tried. I should point out that if I just to a plain __doPostBack("","") I get a full postback and no error when I try to dismiss the dialog.

_doPostBack('Button1','');
__doPostBack("","");
Sys.WebForms.PageRequestManager.getInstance()._doPostBack("","");
document.forms[0].ctl00_ContentPlaceHolderContent_Button1.click();
$find("DlgTasksBehavior").show();

Thanks ... Ed


Hi Ed,

Have you had any luck using the OnOkScript property of the ModalPupupExtender? One way that I use the modal popup is I have an Ok and Cancel button but they may be named differently based on user actions (ie. Cancel may be labelled as Close). I then use the OnOkScript to execute some client JavaScript which then uses a web service to pass the data back to the server for some processing.

OkControlID="btnOk"OnOkScript="modalOkScript()"CancelControlID="btnCancel"

function

modalOkScript(){
//TODO: Add some web service call to take care of my data processing requirements
}

When the Web Service completes, the onSuccess JavaScript function for the webservice in my OnOkScript function changes the 'Cancel' button text to 'Close.

function

onSuccessModalOkScript(result){
$get('btnOk').disabled =true;
$get('btnCancel').value ='Close';
}

Then it's finished and the Modal closes via client side when the user is ready.

Al


Looks like my copy / paste made the JavaScript functions look odd.

Hi, thanks for the reply.

Wouldn't what you suggest be kinda limiting? I wouldn't have access to the various data and controls on the page unless I passed a mountain of parameters the the service call. Seems to me I should just be able to do an async update via the update panel so I can use my server side code to get the job done.

The thing that is a mystery to me is why it is doing a full post back in the first place.I have everything working perfectly it's just the damned blink!

Thanks ... Ed


I have just had a similar situation myself whereby a full postback was occuring whenever I called __doPostBack. Trick is that you have to specifiy the actual client ID in the EventTarget parameter

i.e. _doPostBack('', ''); will NOT work where as _doPostBack('ctl00_textBox1', ''); WILL work. Obviously thats just an example so replace ctl00_textBox1 with your actual clientID value

So my code became:

textJobRef.Attributes.Add("onkeyup","javascript:setTimeout('__doPostBack(\'" + textJobRef.ClientID +"\', \'\')', 0)")

I dont think the timeout is required, but .NET does it so it must be for a reason! :)

Callback Scope on the client

I've started to play around w/ some of the basic Atlas features, mainly calling a web service from the client. One thing I noticed is that scope is lost during the asynchronous call to the server. If my javascript caller & callback method are part of an class, I've no way of telling Atlas to invoke the callback method w/ a specific object's scope.

Is this possible to do?

Cheers,
BobbyYou have a userContext parameter which you can pass as part of yourasynchronous call, that is what you can use to get back to the contextof your call, i.e. you can pass the object who's scope you want back aspart of the call...

Hope that helps,
-Hao
As I understood it, the userContext serves as a holder for contextual data that can be used inside the handler as an object - scope is still lost. Consider the following js class example:

TestClass = function(prop1)
{
this.propertyOne = prop1;

this.test = function()
{
MyCallbackServiceClass.Test({onMethodComplete: this.testCallback, userContext: this});
}

this.testCallback = function(result, user)
{
alert(this.propertyOne);
}
};

var t = new TestClass("This should persist before and after callback");
t.test();

When propertyOne is alerted in the testCallback method, it will be undefined because the scope is not preserved. I don't want the object as a parameter - I want to be operating within that object.
Mike Harder from the ASP.NET team, being the top-notch guy he is, answered this question for me. The scope is maintained by using a delegate.

CSharper.Net.CallbackService.Test({ onMethodComplete: Function.createDelegate(this, this.testCallback), userContext: this });

Call Modal Popup from Javascript

Is it possible to call the Modal Popup from the client side (javascript)? If so what is the code required to do this?Got my answer here: http://damianblog.com/2007/02/28/calling-extenders-from-js/

Hey Chris,

I wrote about this quite some time ago.

Heres a link

http://blogs.msdn.com/phaniraj/archive/2007/02/20/show-and-hide-modalpopupextender-from-javascript.aspx

Hope this helps

Saturday, March 24, 2012

Call Client script from Server Side

Hi All,

I want to call javascript function from server side when I am using updatePanel.

Actual Scenario is as follows:

I have one form A.aspx in which I have a button named "btn_display" and this button is in Update Panel.

Now I call server side function on btn_display_click and from that server side function i want to call javascript function.

How should I proceed??

Plz help

Thanks in advance

HI,
You can use registerclientscriptblock to allow the client script to work from a serverside event

Hello, RegisterStartupScript is more appropriate for this.

Regards. -LV

Call a client JavaScript function after each and every AJAX callback

Hi,

I have a DropDownList, which is enabled or disabled depending on the state of a CheckBox. I am doing this in JavaScript. I have a function which checks the state of the CheckBox, and sets the DropDownList as either enabled or disabled accordingly. I have attached a call to this function to the 'OnClick' attribute of the CheckBox so it gets called each time the CheckBox is used.

All of this is in an UpdatePanel, along with some other functionality which is not directly related. The problem I am having is that each time there is a Postback to the server (or rather I should say a Callback, as we are in an UpdatePanel), the DropDownList is changed to enabled, even if it was disabled before the Callback.

I thought an easy way to solve this would be to call my 'Disable the DropDownList according to the state of the CheckBox' function after each Callback.

So... how can I set my page to call a JavaScript function after each Callback?

Thanks...

Hi,

I'm using this for that task:

function pageLoad( )
{
Sys.WebForms.PageRequestManager.getInstance( ).add_pageLoaded( PageLoadedHandler );
}

function PageLoadedHandler( sender, args )
{
// your code
}

Check ASP.NET AJAX Client Life-Cycle Events for what is pageLoad, also seepageLoaded Event from the same page.



Thanks very much - that is exactly what I needed. I think I need to get down to it and start exploring the whole Sys.WebForms namespace properly.

Thanks again for your help - I'm very grateful.

CalendarExtender: close on client selectes date?

Hi,

just wondering how to make the calendar close when a date is selected...

<

asp:Tablerunat="server"ID="CalendarTable"HorizontalAlign="Center"Width="100%"Height="100%"BackColor="LightGray"><asp:TableRow><asp:TableCellVerticalAlign="Top"><asp:Labelrunat="server"ID="fromDateLabel"Text="from:"CssClass="label"></asp:Label><asp:TextBoxrunat="server"ID="fromTB"CssClass="normal"></asp:TextBox><ajaxToolkit:CalendarExtenderrunat="server"ID="fromCalendar"TargetControlID="fromTB"CssClass="MyCalendar"Animated="true"></ajaxToolkit:CalendarExtender><br/></asp:TableCell><asp:TableCellVerticalAlign="Top"><asp:Labelrunat="server"ID="toDateLabel"Text="to:"CssClass="label"></asp:Label><asp:TextBoxrunat="server"ID="toTB"CssClass="normal"></asp:TextBox><ajaxToolkit:CalendarExtenderrunat="server"ID="toCalendar"TargetControlID="toTB"CssClass="MyCalendar"Animated="true"></ajaxToolkit:CalendarExtender></asp:TableCell><asp:TableCell><asp:Buttonrunat="server"ID="calendarQueryButton"CssClass="button"Text="Search"/></asp:TableCell></asp:TableRow></asp:Table>

I solved this problem by putting

PopupButtonID property to the same textBox


dark_angle:

I solved this problem by putting

PopupButtonID property to the same textBox

I had that. Removed it to solve another issue: with that property set as well, clicking anywhere else on the screen did not dismiss the calendar. And clicking on the second TextBox made a 2nd calendar without dismissing the first...