vb .net ajax call: unknown web method - asp.net

I have seen a few other posts with this error, but I have tried everything suggested in those and am still having an issue.
Here is my webMethod (and class):
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class UPSImportWebServices
Inherits System.Web.Services.WebService
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
<WebMethod()> _
Public Shared Function GetInvoiceItems(ByVal invoiceId As Integer) As List(Of UPSInvoiceItem)
Return UPSInvoiceDataAccess.getInvoiceItems(invoiceId)
End Function
End Class
I just call this on document ready:
$(document).ready(function () {
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~/UPSImportWebServices.asmx/GetInvoiceItems") %>',
data: { invoiceID: "22" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('worked' + data)
},
error: function (response) {
alert('error: ' + response.responseText);
},
failure: function (response) {
alert('failure: ' + response.responseText);
}
});
});
This gives me the error:
Unknown web method GetInvoiceItems. Parameter name: methodname.
EDIT: Changed invoiceID: "22" to invoiceID: 22. Still having the same issue.

I think I figured out the issue. I had copied an existing .asmx file rather than creating a new one. When I went to the url site.com/UPSImportWebServices.asmx, it showed the functions for the web service I copied. I deleted that .asmx file and created a new one and then copied my old code. It is working now.
Also, changed to '{ invoiceId:' + 22 + '}'. Note the ' and the capitalization. Rookie mistakes on this one.

Well, i think this might have to do with the type of variable you are passing. GetInvoiceItems is expecting an integer, you are passing it a string. Try doing changing this
data: { invoiceID: "22" },
to this:
data: { invoiceID: 22 },
and let me know if that works or not. If not, we can move to the next possibility.
Try changing this:
url: '<%=ResolveUrl("~/UPSImportWebServices.asmx/GetInvoiceItems") %>',
to this:
url: 'UPSImportWebServices.asmx/GetInvoiceItems',
and make sure the spelling of your asmx file is correct (case sensitive)
and lastly, try making your method just Public, not Public Shared.

Try doing this.
data: JSON.stringify({ invoiceId: 22 })
The webservice expects a JSON string.
Also, parameters are case sensitive. Your "D" in "invoiceID" is capitalized whereas the web method expects it to be "invoiceId" (lowercase d).

Related

json object returns nothing in WCF data service WebInvoke VB Odata

Hope someone can help. Really pulling my hair out and starting to think i should have not used wcf data services. Its been easy to get odata from the service so i thought i could send json object from my javascript code and read the contents as an object in my service But it returns nothing.
My javascript:
var vname = [];
var obj = { myobject: { frmid: "test", frmval: "1111" } }
vname.push(obj)
$.ajax({
url: "MyWCFDataService.svc/SendItems",
type: "POST",
dataType: "json",
contentType: "json",
data: { myobject: JSON.stringify(vname) },
success: function () {
alert("success :-)");
},
error: function () {
alert("fail :-(");
}
});
My class and function in my svc
<DataServiceKeyAttribute("id")> _
Public Class tobject
Public Property id As Integer
Public Property frmid As String
Public Property frmval As String
End Class
<WebInvoke()> _
Public Function SendItems(myobject As String) As Boolean
' have to ask for string as errors when asking for tobject
Return True ' nothing here yet as cannot get json object
End Function
My first venture into wcf data services and jquery. Was hoping to return a list of textboxes names and values to a wcf data service to process. Is it possible with the wcf data service?
Ok so i created a new wcf data service, removed the inherits dataservice reference and initializeservice sub.
javascript:
vname.push( { frmid: "test", frmval: "1111" })
$.ajax({
url: "MyWCFDataService.svc/SendItems",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { JSON.stringify(vname) },
success: function () {
alert("success :-)");
},
error: function () {
alert("fail :-(");
}
});
service:
Public Class tobject
Public Property frmid As String
Public Property frmval As String
End Class
<OperationContract>
<WebInvoke(ResponseFormat:=WebMessageFormat.Json, RequestFormat:=WebMessageFormat.Json)> _
Public Function SendItems(anyobjectname As List(Of tacosobjectitem)) As Boolean
Return True
End Function
This now turns the anyobjectname into a list of my object. I cant understand why i couldnt use BodyStyle:- Wrapped but it works so im happy. Hope it helps someone out there.

unknown web method using ajax/jquery

ERROR: unknown web method DoIt Parameter name: methodName
I'm trying to pass a date into a DB Query function backended by VB.NET but am having problems with the webside of things.
var dat = $("#Date").val(); //textbox with a date
$.ajax({
type: "POST",
url: "file.aspx/DoIt",
cache: false,
contentType: "application/json; charset=utf-8",
data: {param:dat},
dataType: "json",
success: function (data, status) {
var response = $.parseJSON(data.d);
alert(response.message);
alert(status);
},
error: function (xmlRequest) {
alert(xmlRequest.status + ' \n\r ' + xmlRequest.statusText + '\n\r' + xmlRequest.responseText);
}
});
The file.aspx.vb file:
(at the end of the file)
<System.Web.Services.WebMethod()> _
Public Function DoIt(ByVal param As String) As String
UpdateDB(param) 'function is above
End Function
I'm just not entirely sure whats going wrong or what it means ;/
Check out this answer. You may need to declare the function as Shared
<System.Web.Services.WebMethod()> _
Public Shared Function DoIt(ByVal param As String) As String
UpdateDB(param) 'function is above
End Function
Something that might be worth checking out is to ensure that your database is setup to receive a datetime datatype.
Also something to try in your web-service declaration:
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
<WebMethod()> _
Public Function DoIt(ByVal param As String) As String
UpdateDB(param) 'function is above
End Function
Reference: webservice - unknown web method parameter name methodname

converting object variable to json string for asp.net page method

This is probably a very simple task to perform but I'm taking the risk to ask anyway.
I have an object variable that looks like this:
var MyObj = {"Param1": "Default",
"Param2": "test",
"Param3": 3 };
I'm using ASP.net and I'm looking to pass this object to a page method via jquery.
So far, I have this javascript code:
function LoadObject () {
var TheObject = MyObj.toString();
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: TheObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
I have a page method set up in the .cs file and I put a breakpoint in it but it never gets there; nothing happens.
Please let me know what changes I need to make to get this to work.
Thanks.
You need to serialize TheObject into a JSON string, and ensure that the GetCount method accepts an object with the same signature as TheObject.
I use the jQuery.JSON library to do this so that my syntax becomes:
data: "{ methodParameterName: " + $.toJSON(TheObject) + " }"
I use this library, but you can acheive the same thing with any other library in a similar manner
The first thing that you need to know is that you need to match your method name with your url
for example if your method on your code behind is named "calculate", your url must be something like this "../Pages/TestPage.aspx/calculate"
other thing that you need to keep in mind is the parameters of your method, the names and the types of your parameters must match in you ajax call and your method (code behind)
if the sign of your method is something like this
[WebMethod]
public void Calculate(string data){
// your code here
}
Your ajax call must be like this:
function LoadObject () {
var objetoJson = {
data: JSON.stringify(MyObj)
};
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/Calculate",
data: objetoJson ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
This section is so important:
var objetoJson = {
data: JSON.stringify(MyObj)
};
the name "data" is the name of your parameter in your method (code behind) and "JSON.stringify" is a helper functions already defined on your browser to convert and object to string
Hope this helps
Take a look at this thread: JSON stringify missing from jQuery 1.4.1?
Abstract: jQuery doesn't have a native method to do it. But there are many plugins out there.
EDIT
Sample C# code receiving your JSON object:
[WebMethod]
public static int GetCount(GetCountParams p)
{
// ... Do something with p.Param1, p.Param2, etc.
return 0;
}
public class GetCountParams
{
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
EDIT 2
Sample jQuery AJAX call using that object as parameter:
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: "{ p: '" JSON.stringify(MyObj) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json"
});

Getting jQuery ajax and asp.net webmethod xml response to work

I have an asp.net WebMethod that returns an XmlDocument object.
I can successfully call the method using jquery ajax, but can't seem to get the function to succeed (server side webmethod gets called with correct parameters but client side method fails with 'undefined parser error').
To reproduce, Asp.net C#:
[WebMethod]
public static XmlDocument test(string name)
{
XmlDocument result = new XmlDocument();
XmlElement root = result.CreateElement("Data");
result.AppendChild(root);
XmlElement element = result.CreateElement("AnElement");
element.SetAttribute("Name", name);
root.AppendChild(element);
return result;
}
JavaScript:
function CallForData(name) {
$.ajax({
type: "POST",
url: "AppName.aspx/test",
data: "{'name': " + name+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (response) { ParseXML(response); },
error: function (data, textStat, req) { alert(data + ' - ' + textStat + ' - ' + req); }
});
}
If dataType: "xml" is commented out (automatic) the success function is called but the data is a load of square brackets that seem to indicate an empty json structure.
I want an XML response that I can parse using jQuery.
I think I possibly need to add some format identification to the XML document but aren't sure. Can anyone point out the problem?
Fixed by adding
[System.Web.Script.Services.ScriptMethod(ResponseFormat=System.Web.Script.Services.ResponseFormat.Xml)]
to the web method.
Credit to riteshtandon23 in
this thread

JSON can call method in .aspx file but not in .asmx (ASP.NET web service) file

I am using JQuery & JSON (POST) to call webmethod. However I can call only webmethod located at aspx file but not in asmx file
Below are sample codes
CustomValidate.asmx
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Public Class CustomValidate
Inherits System.Web.Services.WebService
'ACCESS VIA JSON
<System.Web.Services.WebMethod()> _
Public Shared Function AJAX_Test(ByVal date1) As Boolean
...
Return True
End Function
End Class
Javascript: JQuery JSON
function isDates(source, arguments) {
var isValidDate;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CustomValidate.asmx/AJAX_Test",
data: '{date1: "' + arguments.Value + '"}',
dataType: "json",
async: false,
success: function(result) {
isValidDate = result;
},
error: function(httpRequest, textStatus, errorThrown) {
alert("status=" + textStatus + ",error=" + errorThrown);
}
});
arguments.IsValid = isValidDate;
}
It always return javascript undefined error. But if I put the AJAX_Test webmethod in aspx page and replace the url: "CustomValidate.asmx/AJAX_Test" to "mypage.aspx/AJAX_Test". It works fine. Any idea?
You are using what is known as a "Page Method". That is, a static (Shared) method with a [WebMethod] attribute on it. These only work inside of an .ASPX page. They are intended to be used only by JavaScript running on the page.
Try removing the Shared from the method and see if it works better.

Resources