How to call a class method using ajax in c# - c#

I have a class in my c# project. Let's say Sample.cs
I want to call it's method using ajax, but don't know how to use class name in url of ajax, I am doing like this, but it's not working
$.ajax({
type: "POST",
url: "Sample.cs/MethodName",
data: '{Id: "' + Id + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
});
Please Help Guys...

If you directly want to call a method of a class, you cannot.
You can only make HTTP requests calls.
If you are using, MVC, what you can do is that create an Action method with return type as JsonResult, (as from you snippet, it looks you are expecting json response) call your method from this action method and return the same. Or you can create WebApi services and call that method within the ApiController method.

You can also create a WCF Rest service and call it from your js.
You create a method in an interface in C# which will react to your Http request
Here's an example
[OperationContract]
[WebInvoke(Method = "GET", //React on GET method
ResponseFormat = WebMessageFormat.Json, //Return Json format
BodyStyle = WebMessageBodyStyle.Wrapped, //Wrap request and response
UriTemplate = "login/{id}/{mdp}")] //Template Uri
bool Login(string id, string mdp);
This method will be called if you receive a GET method on an url like
SERVER_NAME/login/myId/myPassword
Note : all your parameters must be of type string
If you don't know what is a REST service here's some links
Wikipedia
If you want to learn how to create a REST webService in C# :
codeProject
Sadly I don't have enough point to post more link...
Hope it helped !

Related

.Net asmx webservice not producing json [duplicate]

I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.
However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:
[System.Web.Script.Services.ScriptService]
public class _default : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public string[] UserDetails()
{
return new string[] { "abc", "def" };
}
}
To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the HttpResponse and change the WebMethod return type to void.
[System.Web.Script.Services.ScriptService]
public class WebServiceClass : System.Web.Services.WebService {
[WebMethod]
public void WebMethodName()
{
HttpContext.Current.Response.Write("{property: value}");
}
}
From WebService returns XML even when ResponseFormat set to JSON:
Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.
Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services
This is probably old news by now, but the magic seems to be:
[ScriptService] attribute on web service class
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] on method
Content-type: application/json in request
With those pieces in place, a GET request is successful.
For a HTTP POST
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] on method
and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):
$.ajax({
url: "MyWebService.asmx/MethodName",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ searchString: q }),
success: function (response) {
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ": " + jqXHR.responseText);
}
});
A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.
Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).
Are you calling the web service from client script or on the server side?
You may find sending a content type header to the server will help, e.g.
'application/json; charset=utf-8'
On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.
Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.
I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.

Call code-behind function from javascript in visual webpart

Is it even possible? To call a code-behind c# function from javascript in a visual web part?
It is a complex function so converting all my codes to client side is not an option. I want the logic that is there in this function to happen without a page refresh. This is the background of my issue.
Thanks guys..
You can use jQuery ajax to call server side method and get the response to be used in javascript. This article has simple and good example to show what you need to do.
Code behind
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Javascript
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Why don`t you use a Webservice (Ajax-Enabled WCF Service) which can be called via AJAX?
I think this would be the clean way. Put your logic in an extra class and use this class in the webservice and your webpart. Then you cann call the Method from Code and from Javascript.

calling a PageMethod with params object[] args from jQuery

Is there a way to call a Page Method in jQuery when the page method has a "params" argument type (in C#)?
I can call Page Methods all day long using jQuery if I specify the arguments one at a time, but if I put them as "params object[] args" it throws an error about not finding the "args" parameter.
I am trying to call a method with the following signature:
public static string MakeWebServiceCall(string methodName, params string[] args)
But it only works if I specify it explicitly like this:
public static string MakeWebServiceCall(string methodName, string place, string type, string token)
Just double-check your JavaScript. It's more likely the culprit than a problem with your C#, as the significance of the params reserved word is non-existant. The argument is still ultimately an array of strings, which is nothing special to JSON. I've just built a quick test page which resulted in absolutely no problems using your method. Try double-checking your syntax against the following:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MyPage.aspx/MakeWebServiceCall",
data: '{"methodName":"myMethod", "args":["my","array","of","strings"]}',
dataType: "json"
});
OR if you'd like, stringify a data object using a JavasScript JSON library (native with newer browsers). This method is my personal favorite since I won't have to double-check that I've built my JSON string correctly. Just be sure to enable legacy support for IE7 if you're feeling kind:
var data = {};
data.methodName = "myMethod";
data.args = ["my","array","of","strings"];
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MyPage.aspx/MakeWebServiceCall",
data: JSON.stringify(data),
dataType: "json"
});
If you're having difficulty with some of the particulars of how these arguments are constructed, you might check out this great resource article from Encosia that I go back to frequently just to remind myself of the basics of consuming web services and page methods with jQuery. It explains a couple of the oddities, including links back to pages which talk about why the contentType encoding is important, as well as information as to why the full JSON string must be provided to the data argument rather than just a JavaScript object.

C# Web Service won't output JSON, only XML

I'm trying to use jQuery and JSON with a C# Web Service that I wrote. No matter what, the following code will only output in XML.
Webservice Code
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
return "Hello World!";
}
I also have these attributes assigned to the class
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
jQuery Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ScheduleComputerDS.asmx/HelloWorld",
data: "{}",
dataType: "jsonp",
success: function(data) {
alert(data);
}
});
The ASMX page always returns as content type "text/xml". Anything I'm missing?
EDITS: In response to a couple answers:
If I have the datatype as just "json" the content is still XML and jQuery also will not call my callback function. If I add the "&callback=?" to the url, IIS throws a HTTP 500 error.
My class does inherit from "System.Web.Services.WebService".
From doing some research on your guys answers, it looks like I do need to mess with WCF. Unfortunately the JSON that is returned is more designed for MS Ajax and is a lot of useless bloat for my use. I may look into an open source library like Jayrock or something similar.
Thanks for all your help!
I think there's a typo:
dataType: "jsonp",
Should be:
dataType: "json",
As far as I know, the ScriptService attribute just allows the service to automatically create a JavaScript proxy (by appending /js to the endpoint address - ScheduleComputerDS.asmx/js in your case). It does not allow you to call the operations on the service the way you're trying to do.
You could instead use a RESTful WCF service (which requires .NET 3.5) which you can access by sending a properly shaped URI via an HTTP GET.
Rich Strahl has a really basic post that should help you out with this.
http://www.west-wind.com/weblog/posts/164419.aspx
Have you tried with datatype json?
Also, have a look at Encosia's Using jQuery to Consume ASP.NET JSON Web Services article on the matter. There's some good info on common pitfalls too.

How to let an ASMX file output JSON

I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.
However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:
[System.Web.Script.Services.ScriptService]
public class _default : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public string[] UserDetails()
{
return new string[] { "abc", "def" };
}
}
To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the HttpResponse and change the WebMethod return type to void.
[System.Web.Script.Services.ScriptService]
public class WebServiceClass : System.Web.Services.WebService {
[WebMethod]
public void WebMethodName()
{
HttpContext.Current.Response.Write("{property: value}");
}
}
From WebService returns XML even when ResponseFormat set to JSON:
Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.
Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services
This is probably old news by now, but the magic seems to be:
[ScriptService] attribute on web service class
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] on method
Content-type: application/json in request
With those pieces in place, a GET request is successful.
For a HTTP POST
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] on method
and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):
$.ajax({
url: "MyWebService.asmx/MethodName",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ searchString: q }),
success: function (response) {
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ": " + jqXHR.responseText);
}
});
A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.
Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).
Are you calling the web service from client script or on the server side?
You may find sending a content type header to the server will help, e.g.
'application/json; charset=utf-8'
On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.
Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.
I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.

Categories

Resources