jquery "async = true" call to .net web service not working asynchronously - c#

I have a .NET webservice which I need to hit asynchronously from the jQuery and update the grid based on the result got from service. My problem here is that, the service hit is async only for the first time and the subsequent requests are sync (even after specifying async=true in the ajax call) as shown below
jQuery.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
var result = msg.d;
return callback(result);
},
error: $.callDotNetSM.onError
});
My .NET service method is something like below.
[WebMethod(EnableSession = true)]
public static string GetData()
{
}
So, please help me in calling the service asynchronously all the times. Any help is highly appreciated.

The page your WebMethod is being called on needs to have the following in the Page Directive:
<%# Page Async="true" EnableSessionState="False" %>
The reason for this is that ASP.NET locks the Session every time it is accessed so that it cannot run asynchronously.
Even if you do not use the Session in your WebMethod the page still thinks it uses it by default unless you tell it otherwise.
Edit:
Your problem could also be that you have EnableSession="true". You may just need to set it to false.

Related

Jquery Ajax call to ASMX web service error

I have a ASP.NET Web Forms application that has an ASMX web service file with a single method at the moment. I am trying to call that method from another file in the same project, but it does not seem to be working. When I look at my console window in chrome it states there is an internal 500 error with the web service. using the ASMX interface I am able to manually invoke the method, but it doesn't invoke from my AJAX code. I have been unable to determine the source of my error.
ASMX Web Method
[WebMethod]
public string TestMethod()
{
string x = "{Name:Shooter McGavin}";
return x;
}
JQuery from ASP.NET Page. I know the click event is firing and I also confirmed that the code is progressing inside the IF statement if the form is valid.
$("#AddSupplierBtn").click(function()
{
if ($("#AddSupplier").valid())
{
$.ajax({
type: "POST",
url: "/StockPileDelivery.asmx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.data);
}
});
}
});

In ASP.NET Web Forms, how to call a page method using "get" request

In ASP.NET Web Forms, i am able to call page method using Ajax "post" request. But i am not able to call the page method using "get request".
In this case, is it possible to call page methods using "Get" request.?Could you please provide any suggestion for this?
Example Code for Page method:
[WebMethod]
public static string GetData()
{
return "test";
}
As #vc mentioned in the comments you'll need to make use of the ScriptMethodAttribute as well as WebMethod because you want your request to be GET and not POST so change your code as follows:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetData()
{
return "test";
}
And in the markup you can do
function ShowTestMessage() {
$.ajax({
type: "GET",
url: "YourPage.aspx/GetData",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
<input id="ButtonId" type="button" value="Show Message"
onclick = "ShowTestMessage()" />
Don't forget to add the following reference
using System.Web.Script.Services;
using System.Web.Services;
Ajax GET requests to an ASP.NET Page Method?
I guess the link would be useful. It says For security reasons, ASP.Net AJAX page methods only support POST requests.
Tried decorating the method with [ScriptMethod(UseHttpGet = true)]
but still the get request is not hit.
Also the msdn doc for [ScriptMethod(UseHttpGet = true)]
quotes When this property is set to true, the client proxy code uses HTTP GET to call the Web service. Not sure if it works for a webmethod in web forms.
P.S : Well seems to work with the newer versions of Jquery 2.2.2. Also please be sure that you send data through query strings not using request body as in POST method.

Call method in code-behind (secure page) from client (JavaScript)

Let me start of by saying I am very new to ASP.NET and C#.
I have a simple web form containing data which I want to send to a code-behind page.
The idea is to capture the data and send it as a JSON object to a code-behind method.
Note that this is done via JavaScript/AJAX (see code below).
The code-behind method will then do a trivial HTTP "PUT" request to update the data.
The .apsx page is located in the Secure folder (uses a Secure Master).
Don't know if that will affect the method calling?
Following is the code I have thus far.
JavaScript/AJAX:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "PUT",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
Code-behind:
namespace PartyAtVendors.Secure
{
[WebService]
public partial class Profile : System.Web.UI.Page
{
[WebMethod]
public static bool UpdateVendor(PartyAtApi.Models.Vendors vendor)
{
return true;
}
}
}
Update:
Problem is as follows. The codebehind method isn't called. When I run and test the code and use Chrome's "inspect element" I receive the error:
PUT http://localhost:50671/Secure/Profile.aspx/UpdateVendor 404 (Not Found)
Such static methods are called Page Methods in asp.net.
You call them form javascript like this on the same page as follows:
string data = "{mydata:myvalue}";
PageMethods.UpdateVendor(data);
You need to have a ScriptManager on the page and it should have PageMethods enabled
<asp:ScriptManager runat="server" EnablePageMethods="true">
</asp:ScriptManager>
The page method must be defined on the page. It cannot be defined in a control, master page, or base page.
PageMethods only support HTTP POST(Even when you call them without the javascript proxy of PageMethods). You can read the details of this security limitation in this blog post by Scott Guthrie. Using the PUT verb is causing the 404 error.
ASP.NET AJAX 1.0 by default only allows the HTTP POST verb to be used
when invoking web methods using JSON
Your webmethod & javascript method should be on same page.
Hi managed to sort out what was wrong.
I simply changed the HTTP method to "POST" as follows:
var saveOptions =
{
url: "Profile.aspx/UpdateVendor",
type: "POST",
dataType: 'json',
data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
contentType: "application/json",
success: function (response)
{
}
}
$.ajax(saveOptions);
This seemed to fix the problem and now I am able to send the JSON data to the codebehind method using AJAX.

How to optimize multiple $.ajax({...}) function loading in Asp.net?

I calling multiple function on page load in my asp.net web application.
All function run on page ready method
see the below code
$(document).ready(function(){
func1();
func2();
func3();
//.... so on.
});
function func1()
{
$.ajax({
type: "POST",
url: "Contents.asmx/GetText",
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/some code
}
});
}
function func2()
{
$.ajax({
type: "POST",
url: "Contents.asmx/GetTitles",
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/some code
}
});
}
.... like wise others
For backend I using SQL server-05.
When page is loading It getting more time to load,
above functions takes 30+ seconds to load.
How to optimze function calling?..
You could aggregate all the queries into a new web method which will perform all the SQL queries at once. Then send a single AJAX request to this new method. And as far as your SQL server is concerned you could also send multiple SQL queries into a single round-trip. Try optimizing the SQL queries as much as possible. Also you could cache the results of some expensive queries.
As long as /some code is not too much there is not really much you can do. These ajax calls area light-weight. Your problem is probably in the backend, where you send your requests to.
To debug/profile your problem, first check your ajax requests. Check them in a web-tool like Firebug and see that your request is expected. There you can also check which of your requests takes how long.
As you now see your bottleneck (e.g. requesting Contents.asmx/GetTitles is what takes so long), check your server that provides that page. As you did not provide code of that one, we can not help you there. But that’s where you have to look for next.

jQuery Postback with Webforms

We're redevloping a major section of our website and rather than use a 90k AJAX file I'd rather use a 19K jquery script.
I've seen the following articles;
Using jQuery for AJAX with ASP.NET
Webforms
jQuery autocomplete in ASP.NET webforms?
Autocomplete with ASP.Net MVC and
JQuery
The thing I don't get is how to do a postback to a specific method in either the code behind or another class.
I know in ASP.NET-MVC I can post back to a controller / action. How do I call a particular method in WebForms?
Something along the lines of; $.post("class and action", ( param:value}......
Any thoughts, code etc???
It is very easy to call specific methods in code-behind. Here is nice article with all the details by Dave.
Simply declare a method like this:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
This is all you need in jQuery:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status, xhr) {
// Do something interesting here.
}
});
Caveats:
WebMethod must be on a static method
Must stringify posted data if sending anything (i.e. JSON.stringify(yourDataObject)), will be deserialized according to method parameters
msg is the response, the return result from your method is in the property msg.d

Categories