Why Javascript calling to Page WebMethod results in "500: Unknown web method"? - asp.net

I have a page with this method in CreateTicket.aspx.cs:
[WebMethod()]
public static string Categories()
{
var business = new CategoryBusiness();
var categories = business.ListRootCategories();
return categories.Json();
}
And the javascript/jquery code on the page (same page, .aspx):
function LoadRootCategories() {
PageMethod("CreateTicket.aspx", "Categories", [], LoadCategoriesSucceded, LoadCategoriesFailed);
}
function PageMethod(page, fn, paramArray, successFn, errorFn)
{
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0)
{
for (var i=0; i<paramArray.length; i+=2)
{
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i+1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
Running it on firebug, I get the following error on console:
500 Internal Server Error
Unknown web method Categories.
[ArgumentException: Unknown web method Categories.
Parameter name: methodName]
System.Web.Script.Services.WebServiceData.GetMethodData(String methodName) +517489
System.Web.Handlers.ScriptModule.OnPostAcquireRequestState(Object sender, EventArgs eventArgs) +168
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Why is this happening?

I resolved this problem.
What was happening? Something stupid (as usual):
'Inherits' attribute was missing in the CreateTicket.aspx page declaration, so the CreateTicket.aspx.cs wasn't bound as the partial class, even using the CodeBehind attribute.

Does CreateTicket.aspx inherit from WebService?
Even if it does, your class should also have the ScriptService attribute on it, so that .NET generates additional classes to assist in calling it from JavaScript.
Note: This only applies to non-WCF web services. WCF adds in its own attributes for doing web services.

If you have .NET 3.5 or newer, you can also set up a WCF service.
There's a quick guide on CodeProject on how to set up the OperationsContract and DataContract annotations on your classes in order to create said service.

Related

Action page in asp.net

How do i create a page like an action page in php, in C# ?To be specific I only require a page that contains only methods that handle various operations and return result.
How do i solve the above scenario ?
Create a class, then inside the class create your methods to construct the logic behind your application.
Then reference this class with the using keyword in your web pages and use the methods you created wherever you like.
Read about HttpHandlers.
For example, you want to have a method that returns a json string in a web forms application.
Add a new item to your project of type "Generic Handler". This will create a new .ashx file. The main method of any class that implements IHttpHandler is ProcessRequest.
public void ProcessRequest (HttpContext context) {
if(String.IsNullOrEmpty(context.Request["day"]))
{
context.Response.End();
}
string json = "";
byte[] bytes = getByteArray();
json = JsonConvert.SerializeObject(bytes);
context.Response.ContentType = "text/json";
context.Response.Write(json);
}
Change the url in your AJAX call and that should do it. The JavaScript would look like this , where GetFileHandler.ashx is the name of the IHttpHandler you just created:
$.ajax(
{
type: "POST",
async: true,
url: 'Handlers/GetFileHandler.ashx',
data: "Day=" + $.toJSON(day),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SUCCESS:" + msg);
},
error: function (msg) {
console.log("error:" + msg);
}
});
Read more here for more details.

ASP.NET, AJAX - 403 forbidden

I'm getting the error
**POST http://localhost:34169/createNew.aspx.cs/Confirm 403 (Forbidden) **
when I am trying to call a CodeBehind function with Jquery AJAX.
My code:
function CallConfirmMethod(str) {
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "createNew.aspx.cs/Confirm",
data: "{'smallPos': " + str + "}",
success: function (result) { alert("successful!"); }
});
}
And the CodeBehind function (doesnt actually do anything, just to test things out):
[System.Web.Services.WebMethod(BufferResponse = false)]
protected void Confirm(string str) {
// SKICKA SQL-QUERY
Response.Write("Funktionen kallas! " + str);
}
I think your mistake is in url createNew.aspx.cs/Confirm you should change it to createNew.aspx/Confirm. Also it's good article Calling ASP.Net WebMethod using jQuery AJAX
Maybe you get 500, because you haven't close Response
[System.Web.Services.WebMethod(BufferResponse = false)]
protected void Confirm(string str) {
// SKICKA SQL-QUERY
Response.Clear();
Response.ContentType = "application/text";
Response.StatusCode = 200;
Response.Write("Funktionen kallas! " + str);
Response.Flush();
Response.End();
}
if you want send response in json this is article AJAX to web method not returning JSON

Calling C# collection using Ajax to GridView

Why i get error when i call this collection? All i need to to bind this collection to my Gridview control.....
C# Code:
[WebMethod]
public static List<Customer> GetAllCustomers()
{
using (masterEntities context = new masterEntities())
{
return context.Customer.ToList();
}
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("id");
table.Columns.Add("Name");
table.Columns.Add("Age");
table.Rows.Add();
GridView1.DataSource = table;
GridView1.DataBind();
}
Ajax code:
function GetCustomers() {
$.ajax({
type: "POST",
url: "12.aspx/GetAllCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (data) {
alert(data.d);
}
});
function OnSuccess(data) {
for (var i = 0; i < data.d.length; i++) {
$("#GridView1").append("<tr><td>" + data.d[i].Id + "</td><td>" + data.d[i].Name + "</td><td>" + data.d[i].Age + "</td></tr>");
}
}
This is what i get when i call that collection
http://s22.postimg.org/6qv6tr8g1/aaaaaaaaaaaaaaaaa.jpg
The problem is with the $.ajax error handler:
error: function (data) {
alert(data.d);
}
Error hanlder written like this, gives you very little information on what happened with the failed request. A better way to write your error handler would be like this:
error: function (jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(jqXHR.responseText);
}
With error handler written this way you can look e.g. Chrome Developer Tools's console window and see the value of jqXHR.responseText which contains detailed error description of what went wrong.
Although be careful to replace console.log statements with more meaningful error messages when you deploy your web applications.
Here's a link to jQuery API documentation (look for error handler description): http://api.jquery.com/jQuery.ajax/
Hope this helps!
Regards,
Uros

how to pass a XML parameter to a WEB METHOD using jQuery Ajax

I have a web method that can accept a XElement argument and I want to call it using jQuery Ajax. I can call simple methods using jQuery Ajax with simple argumnets(such as int,string,...), but I don't know how pass to a complex type using jQuery Ajax.
Edit 1)
I have a simple web service :
[WebMethod]
public bool MyGetPassXML(System.Xml.XmlDocument nima)
{
try
{
if (nima == null )
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
For the call I've written this code:
var xmlFragment = 'AB';
$("#Button2").click(function() {
$("#Loader").show();
$.ajax({
type: "POST",
url: "WebService.asmx/MyGetPassXML",
data: "{'nima':'" + xmlFragment + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
$("#Loader").hide();
alert('OK');
}
});
});
I've test it with Firefox and see request an response with FireBug but I get this error:
{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Xml.XmlDocument\u0027","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary2 rawParams)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
I change System.Xml.XmlDocument to XElement but again I get this error. How can I solve this?
Instead of XmlDocument as the web method argument type, I would change it to a string. You can create an XmlDocument from a string by calling .LoadXml(nima).
Edit to answer the request for an example:
Let's say you had a simple class like the following (forgive my c#):
public TestClass {
public string Var1 { get; set; }
public string Var2 { get; set; }
public string void TestClass()
{
}
}
And a web method like the following:
[WebMethod]
public bool MyGetPassJSON(TestClass nima)
{
// do something
}
And your javascript / jquery could look like the following:
$.ajax({
type: "POST",
url: "WebService.asmx/MyGetPassJSON",
data: "{nima: {Var1:'something',Var2:'something else'}}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
$("#Loader").hide();
alert('OK');
}
});
In your case, you could have:
"cities": ["A", "B","C","D"]
This is a very simple example, but much more complex parameters are possible. You can also build up your json as a proper javascript object and use JSON.stringify to send it to your web method.
Construct your XML as a javascript variable and pass that variable as your data into your AJAX call.
var xmlFragment = '<complexType><simple attributeEx="attributeA">A</simple><simple attributeEx="attributeB">B</simple></complexType>';
See http://www.w3schools.com/xml/default.asp for more information on XML.
What you pass in xmlFragment might not be a correct XML because there is no XML declaration.
Also - If you didn't state that anywhere, I don't think your method consumes JSON
I am not familiar with your server side technology, but if you want to send XML type content there is no way to state it in JSON. You have to send stuff like this:
$.ajax({
type: "POST",
url: "WebService.asmx/MyGetPassXML",
data: xmlFragment,
contentType: "application/xml; charset=utf-8", //not sure if charset should be there for xml
dataType: "json", //data type expected in _RESULT_. I have no idea what your method returns
success: function(result) {
$("#Loader").hide();
alert('OK');
}
});
And you might have to change something about your method to receive the whole XML. But this is the only commonly avaliable way to send anything to the server with any indication of XML object type.

consume a asp.net web service that returns json from an stand alone html page

I've developed a web service in asp.net and am able to test it from an in-project aspx page and can readily display the information that was returned in JSON format.
I now need to consume the web service from a stand-alone html page.
Does someone have experience with this? I'm puzzled by the part that would replace this
<asp:ScriptManager ID="ScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~\MyService.asmx" />
</Services>
</asp:ScriptManager>
If this is not possible with straight html and javascript, can someone show me a stand-alone php page that would do it?
See this link:
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
Use JQuery
www.jquery.org
Essentially, you make your Web Service script callable, just an attribute in your Web Service definition and you do:
$.ajax({
type: "POST",
url: "~/MyService.asmx/MyMethod",
data: "{parameterName:'" aStringArgument + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = msg.d
// Now var is an object with properties just like your object
}
});
Use JQUery.
You can use Javascript to access your webservice.
For example - if you have a json webservice defined like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String Foo(String p1, String p2)
{
return "Hello World";
}
you could call it as follow:
var httpobj = getXmlHttpRequestObject();
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest();
else if(window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
}
CallService()
{
//Set the JSON formatted input params
var param = "{'p1' : 'value1', 'p2' : 'value2'}";
//Send it to webservice
if(httpobj.readyState == 4 || httpobj.readyState == 0)
{
httpobj.open("POST", 'service.asmx/' + 'Foo', true);
//Mark the request as JSON and UTF-8
httpobj.setRequestHeader('Content-Type','application/json; charset=utf-8');
httpobj.onreadystatechange = OnSuccess;
httpobj.send(param);
}
}
//Called on successfull webservice calls
OnSuccess()
{
if (httpobj.readyState == 4)
{
//Retrieve the JSON return param
var response = eval("(" + httpobj.responseText + ")");
}
}
If you do not want to use the ScriptManager (which adds over 100k of JS to your page), you can use this method to use jQuery to connect to your web services.

Resources