Create New Asmx Page in asp.net - asp.net

I am creating an asmx web service.
In visual studio 2012 on the project name I right clicked and added an web service name UserDetails.asmx
Now I am trying to use the web service in the js file. like this
$.ajax({
type: "POST",
url: "UserDetails.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function () {
alert("Error");
}
});
Its showing error that POST http: //192.168.9.185/GPS/UserDetails.asmx/HelloWorld 500 (Internal Server Error)
Is there any fault in my code or I am missing something so that its showing error.
My Asmx Page
<%# WebService Language="C#" CodeBehind="~/App_Code/UserDetails.cs" Class="UserDetails" %>
My Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for UserDetails
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class UserDetails : System.Web.Services.WebService {
public UserDetails () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}

Edit
Short Answer: just uncomment [System.Web.Script.Services.ScriptService]
Digging deep in the error message by using
error: function (xhr,status, error) {
alert("Error");
}
and inspecting xhr revealed that the actual error was something else (Only Web services with a [ScriptService] attribute on the class definition can be called from script).
I used [WebMethod] in my aspx code behind and whenever I received such message, I found out that there was an error in the data I am passing. So try adding data:"{}", in your $.ajax()
as described in this post
When making a read-only request, the empty data parameter is the key. For reasons unknown, jQuery does not properly set the specified content-type when there is no data included.

Related

ajax jQuery asp.net error Unexpected token <

I am having trouble adding ajax functionality to existing asp.net 4 website.
I have both tried creating webmethod in the aspx page and also tried asmx, but in both cases I get this error Unexpected token <
this is my jQuery:
function postAssets(datapm) {
$.ajax({
type: "POST",
timeout: 20000,
tryCount: 0,
retryLimit: 10,
url: "talk.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log('success postAssets '+msg.d);
},
complete: function (jqXHR, status) {
if (status == 'success' || status == 'notmodified') {
console.log('complete postAssets' + jqXHR.responseText);
}
},
error: function (req, status, error) {
console.log('error postAssets');
}
});
}
and this is what is in asmx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for talk
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class talk : System.Web.Services.WebService {
public talk () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
I wonder if I am missing any webconfig items, or is it all built in in asp.net 4?
<configuration>
<connectionStrings />
<system.web>
<compilation debug="true" targetFramework="4.0" />
<machineKey validationKey="BA5B68AB87AAEA30753960733E796568" decryptionKey="FAF15E4015737A7695D9761" validation="SHA1" />
<authentication mode="Windows" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
Are you returning JSON or markup? Your call to jQuery's ajax() method is expecting JSON but if you're returning markup that starts with a < character then I could imagine it throwing that exception.
I guess the problem is that you declare your Ajax type as POST while in your ASP Controller you declare HelloWorld() as WebMethods. That's why your ajax can't find your HelloWorld Function.
Try to delete this line:
[WebMethods]
and see if that works.

How to Call Default.aspx.cs page method from Jquery Ajax?

I have a registration form(Default.aspx) which initially show's only 2 field's and a button (Name, email) when user click's on button Jquery makes an Ajax call to Default.aspx.cs function which query db to check for the user, and if it return no then the form expands itself adding registration fields.
I am not able to make a call to Defualt.aspx.cs
my Default.aspx code is :
<script type="text/javascript">
$(document).ready(function() {
$('#btnDownload').click(function() {
//$('#secondary').toggle(1000)
$.ajax({
type: "POST",
url: "Default.aspx/PassData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert('Failed');
}
});
</script>
And Default.aspx.cs is (for test purpose) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private static string PassData(string id)
{
return "Pass";
}
}
But every-time I run the code JS returns error :
Uncaught ReferenceError: com is not defined
POST http://localhost:2305/temp/Default.aspx/PassData 500 (Internal Server Error)
I check few posts but non of them had been answered/resolved.
Any kind of help would be highly appreciated.
Thanks in advance
You need to decorate the method with [WebMethod] attribute.
EDIT
You'll need to add a ScriptManager and use some ASP.NET ajax framework methods. I think what you want to do is impossible with the out-of-the-box functionality.
One option will be to create a HttpHandler that will handle those methods. If the request is a POST, you can find the page type from the url (there's a method in the framework but I can't remember which one, you'll need to investigate), create a new instance and check if the method has the WebMethod (or another attribute you like). If it does, you can call it using reflection and render the result.
EDIT
As #Antony Highsky pointed out, it's possible. I think the solution is to add the [WebMethod] attribute and make de method public (it's private in the example).
Use **[WebMethod]
[WebMethod]
private static string PassData(string id)
{
return "Pass";
}

ASP.NET Web Service to call from JS

I am constantly finding a good guide about how to write a web service using .NET with Visual Studio 2010 so I can utilize it with my HTML based website using AJAX.
I know there was a way called the ASMX way but now it's more updated to ServiceHost so what I need is a simple guide which can drive me through how to create asp.net web service using ServiceHost object.
Sorry if it sounds ambiguous or childish.
Place the ScriptManager control on your page and add a reference to your .asmx service:
<asp:ScriptManager ID="myManager" runat="server">
<Services>
<asp:ServiceReference Path="~/MyService.asmx" />
</Services>
</asp:ScriptManager>
In the code-behind of your web-service declare you web method (notice the ScriptService attribute):
namespace MyServices
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string SayHello(name)
{
return "Hello, " + name;
}
}
}
Now you can consume the web-service from the Javascript like the following:
function queryWebService() {
MyServices.MyService.SayHello('Bobby',
function(result, userContext) {
alert('Web-service response: ' + result);
}, function(result) {
alert('Error!');
});
}
UPDATE
If you want to consume the web-service by simply sending an HTTP GET requests then you can do the following:
Decorate your web-method with a ScriptMethod attribute:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string SayHello(name)
{
return "Hello, " + name;
}
Notice the UseHttpGet property which is set to True. You probably also need to modify the web.config file to allow this kind of interaction:
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
Now you can make a simple HTTP GET request to your web-service like shown below (the example uses jQuery.ajax):
$.ajax({
url: "/MyService.asmx/SayHello?name=Bobby",
success: function(transport) {
alert('Web-service response: ' + transport.responseText);
}
});
Hope this will help you.

How to force ASMX web service to send JSON data to client on HTTP GET request?

I'm trying to use the official jQuery autocomplete plugin with an ASMX web service in an ASP.NET 3.5 Web Forms application. If I understand it correctly, the autocomplete plugin can only use HTTP GET to call a service (with two query string parameters: q and limit). I figured out how to make the web service respond to the HTTP GET calls, but I cannot figure out how to make it return JSON data (even though the service returns JSON data when I call it using jQuery $.ajax with type='POST', when called from the autocomplete plugin it always returns XML). Here are some code snippets:
Web service:
[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
public class UserWS: WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet=true, ResponseFormat=ResponseFormat.Json)]
public List<UserDisplayInfo> GetUsers
(
string q,
int limit
)
{
List<UserDisplayInfo>users = GetUsers(q, limit);
return users.ToList();
}
}
Web page:
$("#test").autocomplete(
"./Services/UserWS.asmx/GetUsers",
{
dataType: 'json',
type: 'POST', // this setting is ignored
contentType: 'application/json;charset=utf-8',
parse: function(data)
{
//...
}
});
If this is not possible I wonder what would be a better alternative:
fixing autocomplete plugin to use HTTP POST and JSON data instead of GET and query string parameters;
using a different autocomplete plugin (I looked at a few, but at this point the official plugin has most recommendations, and I'm not sure if other plugins support HTTP POST);
an alternative to ASMX web service, such as WCF web service (I would not want to use WCF because ASMX web service is simpler to implement -- no web.config changes, no contracts, no interfaces -- and it gives me everything I need);
something else.
I found several similar questions at StackOverflow, but I did not find the answer that would work for me. Any (good) ideas?
Autocomplete plugin wants results in plain text format, not JSON. Each item should be on a separate line:
foo\n
bar\n
baz\n
Try replacing web service with generic handler (.ashx):
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("foo\nbar\nbaz");
}
public bool IsReusable
{
get { return false; }
}
}
On the side note you can't use GET if you want ASMX web service to return JSON. See How to let an ASMX file output JSON.

ASP.NET jQuery error: Unknown Web Method

This is my first time attempting to call an ASP.NET page method from jQuery. I am getting a status 500 error with the responseText message that the web method cannot be found. Here is my jQuery $.ajax call:
function callCancelPlan(activePlanId, ntLogin) {
var paramList = '{"activePlanId":"' + activePlanId + '","ntLogin":"' + ntLogin + '"}';
$.ajax({
type: "POST",
url: "ArpWorkItem.aspx/CancelPlan",
data: paramList,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
alert("success");
},
error: function(xml,textStatus,errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
});
}
And here is the page method I am trying to call:
[WebMethod()]
private static void CancelPlan(int activePlanId, string ntLogin)
{
StrategyRetrievalPresenter presenter = new StrategyRetrievalPresenter();
presenter.CancelExistingPlan(offer, ntLogin);
}
I have tried this by decorating the Web Method with and without the parens'()'. Anyone have an idea?
Your web method needs to be public and static.
Clean the solution and rebuild. I've seen webmethods throw 500's until you do this.
Add public static before your method...
ex.
[WebMethod]
public static string MethodName() {}
For ajax success:
For me, it was helpful to make:
App_Start\RouteConfig
set
from
settings.AutoRedirectMode = RedirectMode.Permanent;
to
settings.AutoRedirectMode = RedirectMode.Off;
make your using method:
public
static
add:
using System.Web.Services;
and on top of method using just:
[WebMethod]
is enough
First Of All Don't Forget To Include
using System.Web.Services;
And Make Sure Your Method Should Be Public And Static and avoid adding Multiple Scripts in same Page like jquerymin.js shouldn't be used for every Function/Method in same Page
[WebMethod]
public static sting MethodName(){}
I Had The Same Issue Which Using Ajax And Jquery To Check Username Exists
Or Not.

Resources