Calling webmethod in code behind from client jQuery - asp.net

I am trying to use jQuery to directly call ASP.NET AJAX page methods. I'm using encosia.com as a reference. My inline javascript is
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
</script>
<div id="Result">Click here for the time.</div>
with my webmethod being
<WebMethod()> _
Public Shared Function GetDate() As String
Return DateTime.Now.ToString()
End Function
I would use FF and check POST sent, but since where I'm at currently only has IE 7 this is a little hard to do. Other relevent information, ASP.net 2.0. Does anyone know what I'm doing wrong?
Update
web.config - pre-existing still not working
<httpModules>
<remove name="FormsAuthentication" />
<remove name="PassportAuthentication" />
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</httpModules>

Since you're using ASP.NET 2.0, you'll need to install the ASP.NET AJAX Extensions, like Joe Enos mentioned. I have a bit more info on the necessary configuration work here: http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/
Additionally, the .d wrapper around the response is an addition that didn't come until ASP.NET 3.5. So, even if you've got everything else working right, your msg.d will be undefined in ASP.NET 2.0. Omit the .d and just make that:
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg);
}

In .NET 2.0, you need to make sure you install the ASP.NET AJAX extensions. In .NET 3.5 and 4.0, the encosia solution works without any modifications.
I don't remember exactly what you need to install, but it might be this.

Have you checked your web.config to allow page methods?
<system.web>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
There is a similar issue here at this post here

Related

I can't get templateUrl to work

I'm new to Angular and I'm using Angular-UI-Router with ASP.NET MVC 4.
app.config(['$urlRouterProvider', '$stateProvider', function ($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('about', {
url: '/',
template: 'HELLO WORLD'
});
}]);
this works fine. HELLO WORLD is displaying so i know that everything is set up rather correctly.
but when i try templateUrl instead of template say:
app.config(['$urlRouterProvider', '$stateProvider', function ($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/'); //if you go to incorrect url it'll go back to home
$stateProvider
.state('about', {
url: '/',
templateUrl: 'Home/About.html'
});
}]);
nothing displays. I'm using almost a clean slate default template from scratch.. picking the "Internet Application" from default templates.. in my directories i have
Views --> Home --> About.html
I also have About.cshtml and I've tried that and it doesn't work neither. Help please!
ASP.NET MVC Views doesn't allow direct access to .html files of it. You need to allow the access from the web.config by adding handlers in system.webServer
Code
<system.webServer>
<handlers>
<add name="JavaScriptHandler" path="*.js" verb="*"
preCondition="integratedMode" type="System.Web.StaticFileHandler" />
<add name="HtmlScriptHandler" path="*.html" verb="*"
preCondition="integratedMode" type="System.Web.StaticFileHandler" />
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
Or the other way around would be you could create one new static folder other than Views that will have an html files in it. You could directly access the URL eg. static/about.html
For more details refer this Answer

ASP.NET Ajax client-side framework failed to load. when put the ScriptManager on a blank page

I have an error Microsoft JScript runtime error: ASP.NET Ajax client-side framework failed to load. on a blank page using masterpage
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="True">
</asp:ScriptManager>
</form>
</body>
</html>
This is what it render it the end
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form method="post" action="WebForm2.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNjE2OTgwNTY5ZGTfWA/dEX85PXBlbkKsVxeLKyIn+mJQ9piW5cbeNE+qww==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="http://ajax.microsoft.com/ajax/4.0/2/WebForms.js" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=6x_aX-LOcgUU-O_K6nM7ST5ViC_naT1e4_j-CY35ASRLpcKYpiapwTARuePHvx3llP-Xhl_AG_ubpM1BzkM5iyn9ThB3m7lmXKvkck0cxTcYiT-VbeKgamKxp9EwxBUyIQN6sSCU9SQm3tMtmzQWRg2&t=ffffffffbad362a4" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script src="/ScriptResource.axd?d=khKEuZ4oUqBYvQxJ1ISpPVIW8_AWWc907q5_v74DI2ruWKTJpldq2osxPkAZ__hffe1Q6HTQUyTbL3Q1mD6MX7V65O5ibxKwb4NvN6ycdZ8vEJ-bz51MO-8uoaP2xioK6npm5n8vldI1d0sOCnH6yw2&t=ffffffffbad362a4" type="text/javascript"></script>
<div>
</div>
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ScriptManager1', 'form1', [], [], [], 90, '');
//]]>
</script>
</form>
</body>
</html>
The problems might be that i used to have AjaxControlToolkit in my project but later i use jquery instead. so somewhere in the project might try to add Ajaxcontroltoolkit which i can't find it. i don't know how to fix this error. i have tried to add bin file of ajaxcontroltoolkit back but it seems to not work.
this solution works for me:
The error on client was:
SCRIPT5022: ASP.NET Ajax client-side framework failed to load.
SCRIPT5009: 'Sys' is undefined
After many time to mining the websites, and more solutions, i solve the problem:
the solution for .NET 4.0 is:
Set EnableCdn property of script manager to true, Like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableCdn="true">
Next Solution and Better Solution is:
add this handler to your web.config
<system.webServer>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
Sys undefined means that you're not getting the client side files loaded on your browser.
Solution 1:
<add verb="GET"
path="ScriptResource.axd"
type="Microsoft.Web.Handlers.ScriptResourceHandler"
validate="false"/>
Solution 2: If you don't have this, add this too under <assemblies>
<add assembly="Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
Solution3: If that doesn't work too, try deleting files from your "bin" folder and rebuild the solution and clear the cache of your browser.
Solution 4: Add this to your web.config
<location path="ScriptResource.axd">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
for telerik web resources use this code:
<location path="Telerik.Web.UI.WebResource.axd">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
I had enabled WebForms Routing and forgot to add the exception for resources:
routes.Ignore("{resource}.axd/{*pathInfo}");
Another possible cause is script combining/compression in IE 8 & 9. In web.config at the top level (within Configuration), put
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true" />
</scripting>
</system.web.extensions>
On your ToolKitScriptManager put CombineScripts=False, e.g.
<asp:ToolkitScriptManager runat="server" CombineScripts="False">
</asp:ToolkitScriptManager>
see http://robmzd.blogspot.com/2010/02/invalid-character-error.html which is where I figured out the problem
Add EnableScriptCombine="False" to your RadScriptManager as follows:
<telerik:RadScriptManager ID="RadScriptManager1" EnableScriptCombine="False" runat="server" />
I had this problem when I moved my forms to a new server. I spent hours to find the solution.
The problem was that the new server has ASP.NET 4.0 and my web.config was ASP.NET 3.5. So I made a new web.config and everything is ok now.
Simply add the <handlers> section as shown below in your web.config within <system.webServer> and this will fix the problem in no time.
<system.webServer>
.
.
.
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
For me it was the problem with Global.asax code,
Just check below condition before validating session in Application_PreRequestHandlerExecute
Request.Path.ToUpper() != Constants.AliasName.ToUpper() + "SCRIPTRESOURCE.AXD"
Functional code is shown below,
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
if ((Request.Path != Constants.DebugLoginUrl) &&
(Request.Path != Constants.SessionTimeOut) &&
(Request.Path.ToUpper() != Constants.AliasName.ToUpper() + "TRACE.AXD") &&
(Request.Path.ToUpper() != Constants.AliasName.ToUpper() + "SCRIPTRESOURCE.AXD"))
{
// to prevent check of HTTP HANDLER FLUSH - Session State is Invalid
if (HttpContext.Current.Session != null)
{
if (Session[Constants.personId] == null)
{
//your code
}
else
{
Response.Redirect(Constants.SessionTimeOut);
}
}
}
In my case the Ajax loading error occurred only if I reloaded the page, not when the page was loaded for the first time.
Looking at the content in the tag in Site.Master, I noticed that only some of the items had Path attribute set. So, I updated MsAjaxBundle to this: and the problem went away. I also had to modify the WebFormsBundle the same way and now reloading the page works.
What worked for me was to download ASP.NET Ajax from Microsoft.
You might also need to explicitly browse for the correct dll version when you add reference e.g.
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\System.Web.Extensions.dll
I set Application Pool as ASP.NET 4.0 Classic during installation.
well i just changed RadScriptManger to Simple asp:ScriptManager and it works
Before:
<telerik:RadScriptManager ID="RadScriptManager1" EnableCdn="true" runat="server" />
After
<asp:ScriptManager ID="scrReg" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
Hope it helps
And here's another cause. I installed MySQL Connector/net 6.9.5. Later I started getting the dreaded 'sys undefined' for everything in some, but not all, projects in IE. Many, many hours later I tried Chrome and Opera and the first page opened fine but on post back all the session variables had vanished. That's when the penny finally dropped - Connector/net must have set itself up the session state provider but I had nothing for session state in web.config for the failing projects. Sessionstate inproc fixed it immediately. At least I think that's what happened...
In my case, I had ended up with the mentioned handlers in <httpHandlers> as well as in <handlers>.
Removing the <httpHandlers> section fixed it.
After adding System.Web.MVC reference to my ASP.NET and added default route in global.asax
i.e.
RouteTable.Routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "new", action = "Index", id = "" });
}
Started getting the error
Added below line to global.asax.cs to resolve it
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
For anyone working with the Visual Studio 2015 ASP.NET 4.5 WebForms Web Application project template which bundles the ASP.NET AJAX scripts:
https://stackoverflow.com/a/47673606/313935
for me web config was correct.
if web config is correct then.
check your IIS App pool settings in my case App pool pipeline was selected as the classic I made pipeline integrated and it started working.
Go to iis -> rightclick on your application pool -> advance settings ->
Managed Pipelined Mode -> "integrated" -> ok
I am using Visual Studio 2015 ASP.NET 4.5 Web Forms Web Application project and apparently a bad route in an API Controller will also cause this error. I fixed the route and the error went away.
It certainly would be nice for a more descriptive error message as to why the client framework won't load. I spent hours checking web.config settings, clearing the .net temporary directories, checking global.ascx, etc.. The strange thing is while IE 11 died while loading default.aspx, chrome was able to load default.aspx and the web site.
Try changing on the web.config the compilation to false:
<compilation debug="false" targetFramework="4.5">
If none of these answers work for you then you might be in my situation.
Ok, so for me the issue was caused by the ssl certificate expiring today, so after I renewed it then these errors went away.

Is it possible to host a WebService in an ASPX page using ASP.Net 2.0?

In the process of converting a page from normal postbacks to AJAX-calls (using JavaScript to load/control the UI entirely and use ASP.Net strictly as a backend), I found myself wanting to replace a GridView with a AJAX-sourced dataset.
I currently use DataTables to prettify the GridView, and there exists an option in the API to use AJAX to remotely source the data for the table. The API needs a JSON object returned, although it appears that I can supply a callback for the fnServerData option which would allow me to convert the XML response to the requisite JSON datasource.
"So", I thought, "I might as well slap together a <WebMethod()> to return the datasource..." and while I've written several <WebMethod()> functions in the past, I've always added a new ASMX file (with a custom class to drive it) or extended an existing one where it made sense to do so. With this specific page, there is no need to make the datasource for this table accessible outside the context of the page, so I thought I would try to add the <WebMethod()> to code-behind of the ASPX page.
There appear to be several examples on the web of programmers successfully pulling off what I have been pulling my hair out over.
I have followed every example that I can find and none are working for me. I have put together an extremely simple example in the hopes that someone can either point out where I'm going wrong or confirm that ASP.Net 2.0 simply won't work in this manner.
ASP Markup:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="AJAXText.aspx.vb" Inherits="_AJAXText" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
<script type="text/javascript" src='<%=Helpers.ToAbsoluteURL("~/_cs/js/jquery-1.6.4.min.js") %>'></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: window.location.href + "/Hello",
data: {
"What": "World"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
$('div').text(textStatus);
},
complete: function (jqXHR, textStatus) {
$('div').text(textStatus);
},
error: function (jqXHR, textStatus, errorThrown) {
$('div').text(textStatus);
}
});
});
</script>
</body>
</html>
Code-Behind:
Imports System.Web.Services
Partial Class _AJAXText
Inherits System.Web.UI.Page
<WebMethod()> _
Public Shared Function Hello(ByVal What As String) As String
Dim msg As String = "Hello, " & What & "!"
Return msg
End Function
End Class
I have tried several little changes to the above, and in every case the AJAX call returns the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
</head>
<body>
<form name="form1" method="post" action="AJAXText.aspx?What=World%2fHello"
id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJOTU4MjMyMzI1ZGQT/2jrJ+cI2ERazl2Hw7l7TI5XiA==" />
</div>
<div></div>
</form>
<script type="text/javascript" src='http://localhost:3719/Maggie/_cs/js/jquery-1.6.4.min.js'></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: window.location.href + "/Hello",
data: {
"What": "World"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
$('div').text(textStatus);
},
complete: function (jqXHR, textStatus) {
$('div').text(textStatus);
},
error: function (jqXHR, textStatus, errorThrown) {
$('div').text(textStatus);
}
});
});
</script>
</body>
</html>
What I expect to be returned is:
<?xml version="1.0" encoding="utf-8"?>
<string>Hello, World!</string>
Does anyone have any ideas:
What I am doing incorrectly?
Or is ASP.Net 2.0 is incapable of using a <WebMethod()> in an ASPX page?
Looks like your data is being provided incorrectly. Should be:
data: "{' + "What" + ':'" + "World" + "'}",
I singled the "What" and "World" out because I assume those are variable values from elsewhere.
so if:
var x = "World";
.ajax(){
.....
.data: "{'What':'" + x + "'}",
would be correct
HTH
Okay, I finally found the complete answer (and +1 to #TheGeekYouNeed for what turned out to be part of the solution).
ASP.Net 2.0 does not support WebMethod() in an ASPX page out-of-the-box. There were three steps total (for me) to enable support of WebMethod() in an ASPX page.
Download and install Microsoft ASP.NET 2.0 AJAX Extensions 1.0.
Add the following to the <httpModules> section of the <system.web> section in my web.config.
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
stringify the JavaScript object being passed to the WebMethod() (and ergo, props to #TheGeekYouNeed). jQuery will automatically convert a JavaScript object to key/value pairs for the query string. The AJAX Extensions, on the other hand, effectively require that a JavaScript object be stringified into JSON (not parsed into key/value pairs for POST[ing] or GET[ting]) as the HTTP Content-Type header must be set to application/json. Since jQuery will not convert data of type string, the JavaScript object must first be stringified into JSON. The JSON string can then be passed with impunity to the AJAX Extensions. There's a lot of information about the stringification being necessary on the web, just search for Invalid JSON primitive. Personally, I thought the best explanation came from Dave Ward over at encosia.com.
UPDATE:
I ran into the same problem on my production server (running the .Net 4.0 Framework on IIS7). To correct the problem on the production server, I had to add the following to the web.config under the <configuration> element:
<system.webServer>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</system.webServer>
Exactly working.
I was researching this problem since last week.
because my local having .NET 4 but due to web server my source has to develop in .Net 2.0
What I have done.
Microsoft ASP.NET 2.0 AJAX Extensions 1.0.
WEB.CONFIG updated/appended exactly what given in [LINK][1] [1]: http://www.asp.net/AJAX/Documentation/Live/ConfiguringASPNETAJAX.aspx

JQuery to asmx fails on Windows 2008 R2 SP1

Since the installation of SP1 we are facing problems in calling asmx pages from JQuery client code.
IIS is pointing the JQuery post call to his default 404 page.
We did a roleback of our environment to assert this issue is caused by SP1 and tests confirm it.
Waiting for a fix #MS
Technologies used:
ASP.Net 4.0 -
JQuery -
IIS 7.5 -
Windows 2008 R2 SP1
--Bart
Code Sample calling (front-end):
// Code to load vars...
$.ajax({
type: "POST",
url: "/Handlers/ProductRating.asmx/RateProduct",
data: "{'uniqueId':'" + uniqueId + "','productId':'" + productId + "','points':" + points.toString() + ",'showOwnScore':" + showOwnScore.toString() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert('success');
},
failure: function(msg) {
alert('something went wrong');
}
});
}
Code back-end:
[ScriptService]
public class ProductRating : System.Web.Services.WebService
{
[WebMethod(EnableSession=true)]
public RateProductResponse RateProduct(Guid uniqueId, Guid productId, int points, bool showOwnScore)
{
//Implementation
}
Snapshot1 : With SP1:
http://img812.imageshack.us/i/capture2r.png/
Snapshot2 : Without SP1:
http://img190.imageshack.us/i/capture1qx.png/
I was able to get this working with the following addition to my web.config
I saw another site that suggested clearing the handlers, but that made everything way worse. With this update, I was able to call my web services once again.
<system.webServer>
<handlers>
<add name="AsmxRoutingHandler" verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</handlers>
</system.webServer>
I had the same problem.
Create a Web.Config file containing the following lines:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.web>
<httpHandlers>
<clear />
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add path="*" verb="GET,HEAD,POST" type="System.Web.DefaultHttpHandler" validate="True" />
</httpHandlers>
</system.web>
</location>
</configuration>
Copy this into the directory(s) where you serve out your affected scripts, and restart your web server.
These lines will override your preferred HttpHandlers and set it to use the default handlers instead.
Good luck!
Judging by your screenshots, that seems an awful lot like a URL rewriting issue. Does your site have any overly-greedy URL rewrite rules at the IIS level that could be 302 redirecting /Handlers/ProductRating.asmx/RateProduct?
If you do have rewrite rules, can you try disabling them temporarily to see if that fixes the ASMX issue?

Error while accessing ASP.net webservice using JQuery - JSONP

Please look at the code below and help me to figure out what am I doing wrong in my web service code. I want to set up an asp.net web service that can be consumed using an JSONP. I am using Jquery at client side to access the site. Even after setting up proper attributes my web service still emits xml due to which the aynch call fails.
Web Service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json, XmlSerializeString=false, UseHttpGet=true)]
public string HelloWorld(int id, string __callback) {
return __callback + "({message: 'Hello World'})";
}
}
Web Service Response:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">test({message: 'Hello World'})</string>
Web.Config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd"
type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"
validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule"
type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
Javascript
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:54404/jsonp/webservice.asmx/HelloWorld?id=2&__callback=?", //?jsonp=MatchSvcCallback
dataType: "jsonp",
data: {},
//jsonp : "MatchSvcCallback",
success: function(msg) {
alert("Inside success callback function"); // not being called
},
error: function(xhr, msg){
var response = JSON.parse(xhr.responseText);
}
});
The js code works with an handler, but fails for the webservice due to xml response.
I think the problem here is because jQuery doesn't set the Content-Type header in the HTTP request for HTTP GET's when using $.ajax(). It only gets sent if the request type is 'POST'. This seems to be the case for both dataType: "jsonp" and dataType: "json".
I tried your example and watched the request/response exchange in Fiddler and sure enough I don't see Content-Type: application/xml; charset=UTF-8 being sent in the headers for HTTP GET requests. The header does get sent if using HTTP POST. I'm guessing the presence of this header is a cue for the ASP.NET web service plumbing to decide whether to return either a JSON or XML formatted response.
It seems you're not the only one with this problem, see the following article on the on Elegant Code website:
Calling Remote ASP.NET Web Services from JQuery
The solution appears to be one of the following:
Use a HttpModule to inject the Content-Type: application/xml; charset=UTF-8 header into the request stream as described in the article above.
Use a HttpHandler for the endpoint as you explained you were doing prior to using an ASP.NET web service.
Try Rick Strahl's page based approach
in the following article (which
is in effect a HttpHandler anyway): JSONP for cross-site Callbacks.

Resources