Wednesday, March 28, 2012

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 simple JS Function in the "Atlas way"

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

Thanks in Advance for the attention,
Fract4L

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


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

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

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

JoeWeb


hello.

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

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


Hello all,

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


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

Fract4L

Here is the code:

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

hello.

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

Calling a server side method.

My experience lies with Ajax.net. I need to call a method passing parameters back on the server. What ATLAS methodology should I do?

Imagine the scenario where I have a ordered list and I have the option client side to change the order. After each order change (the client UI is modified), I need to just touch a method on the server. I don't need any response or updates back.

I would like to do something like this

function OnItemMoved( first, second )
{
AltasCall.MovingObject.MoveItems( first.ID, second.ID );
}

Hi,

a PageMethod seems appropriate for your scenario. Basically you have to add the [WebMethod] attribute on your server method (you have to declare this method in your Page class), make it public and then you will be able to call it on client side through the PageMethods namespace:

function OnItemMoved( first, second )
{
PageMethods.MyMethod(first, second);
}

I appreciate it greatly, works like a charm.

Do you know if it is possible to call another method outside the Page class's scope? This is library code, and I don't want to force the end user to declare this method on all their pages.


billrob458:


Do you know if it is possible to call another method outside the Page class's scope?


At the moment the methods must be put in the Page class. One solution to your problem would be to wrap the library method with a WebMethod and put it in a base class that inherits from Page. The other pages will then be derived from the base class.
Another solution would be to expose the reusable method as a web service - which can act as a wrapper for your library code. Then you can make the calls to the webservice from anywhere.

calling a server side method to rebind and refresh a datalist in updatepanel without a ful

I have 2 datalists:

datalist1 (inside UpdatePanel1)

datalist2 (outside UpdatePanel1)

I have a ImageButton inside the datalist2 & when it is clicked, in the datalist2_ItemCommand event, I am updating some information in the database & calling a DataBind() on datalist1 & then calling an Update() method of UpdatePanel1.

This works fine, but my problem is that because of the datalist2_ItemCommand getting fired, a full postback occurs as well. How do I avoid this? I just want the datalist1 to be refreshed inside the UpdatePanel & not refresh the datalist2 at all.

If I use Web Service method, then I can do the database update in it, but I am unable to access the datalist1 to rebind it and also the UpdatePanel1 to update it.

Can someone please help me.

Thanks

Hi,

You canregister theItemCommand event ofdatalist2as a trigger of the UpdatePanel in whichdatalist1 is contained.

<Triggers>
<asp:AsyncPostBackTrigger ControlID="DataList1" EventName="ItemCommand" />
</Triggers>

Best Regards,


I had logged this issue in another forum my mistake and it got moved in this forum only after I logged it again as a new post (link below):

http://forums.asp.net/p/1180380/2000803.aspx#2000803

Thanks for your help.

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