Wednesday, March 28, 2012

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