Showing posts with label page. Show all posts
Showing posts with label page. 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 functions

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

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

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

What and where exactly you want to do?

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

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

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

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


Yo can use for calling javascript function

Registering Custom Script

from ScriptManager

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

For calling server side function use web services..


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


Hi,

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

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

Sys.Application.add_load(ApplicationLoadHandler)

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


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


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

Sys.Application.add_load(ApplicationLoadHandler)

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


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

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


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

Then invoke it at client side.

Please read this:

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

calling javascript function 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 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 web service in a javascript causes page reload

Hey guys,

Here is what is happening. I have a user control in which I have an update panel with a button and some label. On click of that button, I call a javascript function which in turn calls a web service. The web service does get called and everything works nicely, but the whole page is being refreshed. The moment the javascript calls a web service, the refresh of the whole page occurs (when in turn nothing should happen besides the web service called).

Do I have something misconfigured that causes the script manager to do the whole page refresh on a web service call? I have the same structure in another control, and that one doesn't cause the page refresh.

If anyone has experienced this and have a solution for it, I would love to hear it.

Thanks!

Are you using Server Button Control(<asp:Button/>) of usual html button(<input type="button"> ?

I'm assuming you have something like:

<asp:Button ... OnClientClick="CallMyWebService()" />

or

<input type="button" ... onclick="CallMyWebService()" />

Try making it "CallMyWebService(); return false;"... the "return false" tells the browser not to continue handling the event (by submitting the form, for example). If that's not it, you might try showing us your code.

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 web service from a secure site

I have hooked into a web service from our site and it has worked fine throughout development. Now that we've pushed the site live, the page that calls the service is a secure page and I get a javascript error on a line 3210. I'm assuming it's in the Atlas.js file (since I'm using Atlas to call the web service). That line says

_requestor.open('POST', _effectiveUrl,true);

I'm not sure what to do to fix this or if it's possible to fix it since I'm calling it from a secure page. Has anyone run into anything like this before and if so, how do you get around it? Or is it impossible to call an unsecure web service from a secure page? Thanks.

The browser generally limits calls from secure to unsecure pages. Is there any way you can put the web service on the same secure site?

thanks,
David


I'm having almost the same problem... the only difference is that the page is not a secure page...


Well, the service the page is calling is located on the same secure domain as the secure page. And in the atlas:ServiceReference Path, I specify the full secure url. It is in this service on the secure site that it calls the unsecure service. So, I would think that the browser wouldn't really know anything about the unsecure service since it's only calling a secure service. Unfortunately the unsecure service is not mine and I have no way to secure it. Is there any other type of work around for this? Thanks.

So if I understand correctly:

Your page in on the secure server. e.g.https://www.srv.com/app/page.aspx
Yes, you've got it. That's exactly how it's set up. The secure page calls a web service through Atlas on the same secure server. That service has a web reference set up to a non secure service. That's what I was afraid of, but I'm not sure then why it works if I go to the page as an unsecure url.

But where is the failure point? I assume that the call from Javascript to the secure server is correctly happening, and that it is the second call to the non-secure service that is failing?

If so, I would think this would happen without Atlas in the picture. e.g. if you make the same non-secure call from your page's Page_Load() method, does it fail in the same way?


Unfortunately because this is not on a my local box, I can't do any real step through debugging, but according to the error message, it looks like it's occurring in the atlas javascript call to the 1st (secure) service in atlas.js, line 3210, _requestor.open('POST', _effectiveUrl, true);.
I just tried something and found something interesting. I modified the atlas.js file and put an alert right before the line that's erroring with the url of the service it's trying to call. Even though I setup the serverreference path ashttps://secure..., when it alerts, it's coming back ashttp://secure... When I view source, the reference is still there as https, so I'm not sure why atlas is treating it as http. Maybe I'll have to just redo this in traditional ajax and forgo the Atlas handling.

Calling a static page method using Asp.net AJAX and then clicking elsewhere on the page

Hi All! I seem to have reached a snag and hoping someone out there can help me...Basically, I am letting the user click a button on my site which uses AJAX to call a static page method on my page which runs a complicated query in my database. The query can take up to 5 minutes to complete so I wanted to use AJAX to let the user still surf my site while the query was running in the background. However, once the user clicks on a button and tries to navigate anywhere else on the site the browser gets "stuck". It won't let you surf anywhere else...it sort of just hangs there until the browser receives a message back form the server saying the query succeeded or failed. I thought you can make more than one web service call at once? If you can't, is there a way to make a call to the server, but not necessarily wait back for a response?

Any help would be appreciated. Thanks!

The Ajax webservice/pagemethod call is always async, you should be able to do the other operations in the page. Can you pls post your code, so that we can verify it.


Below is my aspx code:

<scriptlanguage="javascript"type="text/javascript">

// <!CDATA[

function Button1_onclick() {

PageMethods.WriteReport(OnSucceeded);

}

function OnSucceeded(result)

{

$get('GenerateLabel').innerHTML = result;

}

// ]]>

</script>

</head>

<bodystyle="text-align: center">

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

<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="True"/>

<inputid="Button1"style="position: relative"type="button"value="Run Report"onclick="Button1_onclick()"/>

This is my code behind page:

[WebMethod]publicstaticString WriteReport()

{

String UserName =HttpContext.Current.User.Identity.Name;

int reportsID = (int)HttpContext.Current.Session["reportsID"];

Reports rep = (Reports)HttpContext.Current.Session["Report"];

try

{

Sharing.WriteActualReport(reportsID, rep, UserName); //This is the method that takes a few minutes to complete and where it get stuck.

}

catch (Exception)

{

return"An error occurred."

}

return"Success!";

}


There is nothing wrong in your code. You should be able to do any thing when the method is in progress. but what other operations you are trying to do?


KaziManzurRashidsuggested the following solution which worked on my computer. I'm still not sure why calling a static page method still stalls my site (on my computer), but the below code seemed to work well:

KaziManzurRashid:

No i did not encounter that, I was able to click different parts of the page. [Edited] It is not a good practise to run such a long process in the server. However, you can utilize the ThreadPool to generate this report in the server. in that case the the message will be returnded instantly to the user. May be the following will code will help you:

[WebMethod()]public string GenerateReport(string param1,string param2){ System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(GenerateReportInternal),new object[] { param1, param2 });return"Report generation started";}private void GenerateReportInternal(object state){object[] pair = (object[])state;string param1 = (string)pair[0];string param2 = (string)pair[1];//Generate your Report over here. //Fake delay for your test. System.Threading.Thread.Sleep(1000 * 60 * 5);}

Thanks again!

Calling a simple Web Service from an ASPX page

Hi

I created a new Atlas web project, added a new web service and web page using the the code from the Simple.aspx and SimpleService.asmx.

Given I have identical code in the page and ws, I end up with 'Quickstart' is undefined error, on the following line of javascript:

requestSimpleService = Quickstart.Samples.SimpleService.EchoString(
document.getElementById('inputName').value, //params
OnComplete, //Complete event
OnTimeout //Timeout event
);

Any ideas?

It turns out in VS2005, when a new web service is created a code-behind is also created and placed into the App_Code directory. The problem I was getting was becuase the namespace reference was not the same as in the asmx.

Problem solved.


Great! Note that this behavior is optional, so if you prefer you can get the code inline in the asmx file (it's a checkbox on the add dialog).

David

Calling a server side method from javascript without page methods

Hi everyone.

I'm trying to do some like this:

if (confirm("foo") == true) {

MyServerSideFunction();

}

Of course, I can call this function using PageMethods, but since this function in my code behind shold be static, I cannot call others methods inside my class.

Is there any way to call serer side methods without using PageMethods?

Thanks, and sorry for my bad english!

You can use ajax to call a webservice from javascript. Check out this article on how to do it:http://www.semenoff.dk/en/Code-Corner/ASP.Net.AJAX/WebService-From-JavaScript.aspx

Hope it helps


__doPostBack("ServerEventNameHere","");


Hi Everyone :)

@.Klaus Byskov Pedersen

I alread tryed using web services and it works fine, but it's not the case.

@.rpack79

Nice! It works! I noticed that I had to catch this requent inside my OnPageLoad and call the appropriated methods. Now one more question: And if I want do catch this postback inside an WebControl? Actualy I'm catching the postback event inside my control's OnInit event. Is it the right way?

Thanks a lot by the answers.

Calling a Page Method Instead of a Web service method with javascript?

Hi All,

I am just wondering if it is possible to call a page method or a static method (non webservice) with javascript and have it return the results to the calling javascript funciton just like how it is done with a webservice call? Personally I prefer not to be producing asmx's for things that may only be used on a single page.

If so ... how might I accomplish this?

If Not.... Why not?

hehe

Thanks

Hi miskiw

Yes you can do that, you can find details here

http://ajax.asp.net/docs/tutorials/useWebServiceProxy.aspx at the bottom of the page titled "To call a static page method".

It is worth noting that there is a bug with this in the current release where you can only call methods that are inline. You cannot currently make async calls to methods that are in code behind.

HTH

Andy.


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

can't open.

can you give a sample?THX


The new address is:http://ajax.asp.net/docs/tutorials/ExposingWebServicesToAJAXTutorial.aspx
In the bottom of the page, you have the section Exposing Web Services from an ASP.NET Web Page.

Basically, what you need to do is to create a static method and apply the [WebMethod] attribute to it.

[WebMethod]public static string EchoString(string name) {return"Called by " + name +".";}
HTH,
Maíra

Calling a JS function from server side

Hi,

I try to call a javascript function from the server side but it doesn't work, here my code :

1<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>23<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">45<html xmlns="http://www.w3.org/1999/xhtml" >6<head runat="server">7 <title>Test</title>8</head>9<body>10 <form id="form1" runat="server">1112 <atlas:ScriptManager ID="scriptManager1" runat="server" EnablePartialRendering="true"></atlas:ScriptManager>1314 <atlas:UpdatePanel ID="UpdatePanel1" runat="server">15 <ContentTemplate>1617 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />18 <asp:TextBox ID="TextBox2" runat="server" Text="test"></asp:TextBox><br />19 <asp:Button ID="Button1" runat="server" Text="Write" OnClick="Button1_Click" />20 <asp:Button ID="Button2" runat="server" Text="Clear" OnClick="Button2_Click" />2122 </ContentTemplate>23 <Triggers>24 <atlas:ControlEventTrigger ControlID="Button1" EventName="Click" />25 <atlas:ControlEventTrigger ControlID="Button2" EventName="Click" />26 <atlas:ControlValueTrigger ControlID="TextBox1" PropertyName="Text" />27 </Triggers>28 </atlas:UpdatePanel>2930 </form>31</body>32</html>33

And the code behind :

1using System;2using System.Data;3using System.Configuration;4using System.Collections;5using System.Web;6using System.Web.Security;7using System.Web.UI;8using System.Web.UI.WebControls;9using System.Web.UI.WebControls.WebParts;10using System.Web.UI.HtmlControls;1112public partialclass test : System.Web.UI.Page13{14protected void Page_Load(object sender, EventArgs e)15 {1617 }1819public void Button1_Click(object sender, EventArgs e)20 {21 TextBox1.Text ="Button clicked";22 }2324public void Button2_Click(object sender, EventArgs e)25 {26 TextBox1.Text ="";27 Response.Write("<script type=\"text/javascript\">alert('hello');</script>");28 }2930}31

When i click on the button 2, my alert function is not called and the textbox 1 is not cleaned.

How can i call the JS function ?

Take a look at this post:http://forums.asp.net/thread/1395511.aspx
thank you :)

copy this code atButton2_Click

public void Button2_Click(object sender, EventArgs e)
25 {
26 TextBox1.Text ="";
27 Page.ClientScript.RegisterStartupScript(typeof(Page), "OnLoad", "alert('hello');",true );
28 }

See more details athttp://forums.asp.net/thread/1403704.aspx

Monday, March 26, 2012

Callback returns wrong SQL results!

I have a page that has buttons to change values in a few tables. When I use Postbacks it works fine, when I AJAXify it it shows the same results as it did before. Here's the strange bit, if I make a second change it shows the expected results from the first change and so on. It seems to always be one change behind.

I'm going to make a very small version of the page and post it here if it still happens.

It is only happening on one table. It is a very large table but I shouldn't think that would matter if the original Postback method works fine.

Does your AJAX.NET enabled page use a full Web Service? If so you install WSE 3.0 and turn on the trace utiliy. This should show what is being sent and recieve.

CallBack on ContentPageHolder

Hi everyone,

I have a Master Page called AppMaster.master And I have two aspx pages: Default.aspx and News.aspx.

On my AppMaster.master i have one Menu (top of the page) and Ads (left and right of the page). I have a ContentPlaceHolder in AppMaster. When i click on Home the page refresh and go to /Default.aspx, the same thing for /News.aspx.

I want to refresh only the content of the masterpage using callback or AJAX. I probed two methods but i can't refresh only the content. When i click news on the menu of the master page refresh only the content showing /News.aspx without postback. I used the updatepanel but it does'n work.

Can you help me please? Thanks...Confused

This is your scenario?

1) You have a master page,

2) You have two content pages that use the master page,

3) You want to refresh the UpdatePanel on the content page when someone clicks a link on the Master Page?

Check this out, and if this does not help you then let me know:http://www.ben-rush.net/blog/PermaLink.aspx?guid=d29bafbb-35f5-425e-9105-c1ddaae3b003&dotnet.

...it's possible I don't understand exactly what you're trying to do.


Option 3. I have a Menu with the MenuItemClick method.

Thank you very much...


Option 3. I have a Menu with the MenuItemClick method. It doesn't work because new MenuEventArgs doesn't work :(

Thank you very much...

CAllback Http handler http module

Hi all,

Can anybody tell me how to generate callback.This call back should NOT be in on aspx page .

I this its solution is Http module or Http handler but i dont have idea to implement .Give me some reference and sample code or examples for implementing call back using http handlers or httpmodule

thanks

Could you please describe in more detail what you want? A callback (as in ICallbackEventHandler) that is not on a page does not make sense.


I HAVE A WEB CONTROL CLASS LIBRARY IN WHICH I HAVE A .js FILE ADDED AS RESOURCE FILE . FROM THIS FILE I WANT TO SEND A CALL BACK AS I WANT TO USE "AJAX". BUT AS FAR I KNOW I REQUIRES A .aspx.cs PAGE WHICH I CAN'T ADD IN THE CLASS LIBRARY. HOW WILL I DO THIS TASK.

ANY KIND OF HELP IS APPRECIATED


ICallbackEventtHandler can be implmented in a Controt, it not true that it can be only implmented in a page. For more details of creating controls with ICallbackeventHandler checkout this articlehttp://msdn.microsoft.com/msdnmag/issues/05/01/CuttingEdge/default.aspx

Call webmethod in page possible

I thought it was possible to call a public method with the attribute [WebMethod()] above it. But when I try out the sample of the AutoCompleteExtender it works perfectly when I put the code in a webservice (.asmx). Unfortunately when I put the same code in my default.aspx page it doesn't work.

I changed the ServicePath to ="Default.aspx" but that doesn't seem to do the trick.

So does anyone have a clue here what I'm doing wrong?Hi,

at the moment the auto complete stuff works only with a web service. Page methods are not supported.
However, do a search in this forum since a user (I can't remember the name, sorry) has coded a custom version that supports page methods.

Jay Kimble is your man.

http://david.codebetter.com/blogs/jay.kimble/archive/2006/07/17/147436.aspx


The auto complete extender in my library also supports this.

Call WebMethod declared on a DIFFERENT aspx page?

I'd like to expose a WebMethod on an ASPX page and then invoke it from my Atlas page:

<atlas:ScriptManagerrunat="server"ID="scriptManager">

<services>

<atlas:servicereferencepath="MyAspxBasedService.aspx"type="text/javascript"/>

</services>

</atlas:ScriptManager>

Then invoke it. The reason is that I want the full ASPX processing to happen. In short, I want to declaratively create controls on the ASPX page, then render partial pieces of them to be returned back to the Atlas client.

Any help?

Tad

Just as I sent, I noticed that you wanted to call a page method on adifferent page, so clearly PageMethods.YourMethodName() won't work.

Calling a method on a different page is not supported. I'm not convinced that this is desirable; when you call a method on the current page, the point is that the server page gets populated with all the data from the browser, and that your method can make use of it. But if it's a different page, it can only have its clean original state, which seems a lot less useful.

David


Hi Tad,

You don't need to use any servicereference to call a method that's on the page itself. Just mark the method with a [WebMethod] attribute, and call it using the name PageMethods.YourMethodName(...).

David


Thanks David.

I've got a flyout asp:Menu control on my site that is 3 levels deep, which bulks up the page size and is pig slow. I thought about seeing if I could get the same benefits of the control by making it populate on demand. So, my ASPX call will pass a parameter indicating which branch of my menu I need to render (from my database). I would use the menu control to programmatically build the branch and render the html which I'd return from my webservice call. (of course I'd cache it too).

The nice thing about the ASPX page is that I can declaratively define the menu properties and templates.

I suppose I could make an XmlHttpRequest directly to the ASPX and pass query string params, but that seems soooooo YESTERDAY!

I'm just foolin' around. Any ideas before I go off and just build my own lightweight flyout control?

Tad


Why not use a Web Service that provides your site navigation menu data that takes, as input, information indicating the current branch that the page is on? Atlas is definitely designed for dealing with that type of scenario, and the 'pig slow' effect can be mitigated by having bits of your menu populated dynamically asynchronously using the Web Service invocation.

Obviously if you're tied to only using an ASPx page, then thats that...but one of the first things I did with Atlas was whip out a dynamically-generated site navigator that was powered by a Web Service. I was really impressed with it.


I wouldn't attempt that myself. Plus, I don't think a flyout menu is the right control for on-demand population (which is exactly why we didn't include the feature in the first place). Imagine what will hapen if the user flies his mouse cursor over the menu (which he'll necessarily do unvoluntarily): tens of requests sent to the server at the same time. Ugly.

Developing a lighter menu with fewer features but with focus on CSS without inline styles is probably a much better option. I was thinking of doing that when I have some time (which probably means not in the next few weeks).


Sure, that's a good point, and even without using a web service and dynamic population, reducing the depth of the menu and starting at the current hierarchy level can help considerably.

A combination of a menu and a SiteMapPath can give a good navigation UI without going too fancy.

About what you describe, the thing is that the menu does not support populate on demand. A treeView would do the trick, but that may not be the UI you want (although the TreeView appearance can be brought close to that of a menu with the exception of the fly-outs).

Call Server Side method from JavaScript function in Master Page

I have a JavaScript function in a Master Page. The function is below.

function Add(q, p) {//call server side method }

I want to be able from within the JavaScript Add function defined above, call a C# server side method and pass the values q and p to it. No value is returned.

I have tried PageMethods.CallServerSideMethod(q, p); but it will only work in a Page, not a master page.

Is there any way I can do this in a master page?

How about using a web service call?

Thanks for your help.

How could i code that? An example maybe?


The documentation has pretty good code examples. See if this helps: http://www.asp.net/AJAX/Documentation/Live/tutorials/ExposingWebServicesToAJAXTutorial.aspx

Niall20:

it will only work in a Page, not a master page.

That's because .master file can't work as a httpHandler to server the request. It's blocked. In a simple word, the method in master page can't be accessed from client side directly.

Call out

I want to create a call out on mouse over. I have some small text on a page and when you mouse over it i want it to do a call out. so the text i big. Can this be done?

Thanks
Mike

Mike,

You may want to think about a Javascript solution like the one here:http://www.dynamicdrive.com/dynamicindex5/popinfo2.htm


how would i do that with data from a database?

Mike


Hi Mike ,
I think you can add a WebService to your page and the WebService will get the result from your Database. Here is the sample shows how to use Call a WebService on the client. The sample is written by Jerferry zhao.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="Services/UseHttpGetService.asmx" InlineScript="true" />
</Services>
</asp:ScriptManager>

<input type="button" value="Get Random" onclick="getRandom()" />
<input type="button" value="Get Range Random" onclick="getRandom(50, 100)" />

<script language="javascript" type="text/javascript">
function getRandom(minValue, maxValue)
{
if (arguments.length != 2)
{
UseHttpGetService.GetRandom(onSucceeded);
}
else
{
UseHttpGetService.GetRangeRandom(minValue, maxValue, onSucceeded);
}
}

function onSucceeded(result)
{
alert(result);
}
</script>

WebService

<%@. WebService Language="C#" Class="UseHttpGetService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UseHttpGetService : System.Web.Services.WebService
{
[WebMethod]
public int GetRandom()
{
return new Random(DateTime.Now.Millisecond).Next();
}

[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public int GetRangeRandom(int minValue, int maxValue)
{
return new Random(DateTime.Now.Millisecond).Next(minValue, maxValue);
}
}

I hope this help.

Best regards,

Jonathan