My jQuery ajax doesn't work - asp.net

Just started to learn jQuery ajax today, followed what tutorial said but it did not work.
HelloWorld is the method name, but it seems not be recognized as a method name but a page name based on the error message.
jQuery
$(document).ready(function () {
//alert("hello world");
$('.ordernumber').on('click', function () {
var orderNum = $(this).text();
$.ajax({
type: "POST",
url: "./OrderDetail.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
// Do interesting things here.
}
});
//alert($(this).text());
});
});
OrderDetail.asmx.vb
Imports System
Imports System.Web.Services
Public Class OrderDetail
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function HelloWorld() As String
Return "Hello World"
End Function
End Class
Error Message:
POST http://localhost:64616/OrderDetail.asmx/HelloWorld 500 (Internal Server Error)

I think you need to add <System.Web.Script.Services.ScriptService()> to your class;
<System.Web.Script.Services.ScriptService()> _
Public Class OrderDetails
Inherits System.Web.Services.WebService
'' rest of your code
End Class
Also to return Json you need to decorate your methods with;
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Update
When creating a fresh ASMX Web Service, the default code states;
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _

You are expecting a JSON back, but an asmx webservice returns a XML instead you need to add
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>_
Public Function HelloWorld() As String
Return "Hello World"
End Function
The link for more explanaiton

Related

allow webservice to be called from script

hi there i have a demo page in my web site, i am learning how to call webservice from script
this is my page
http://applicazioni.vsc300.it/Mediweb2015/Prova.aspx
$(document).ready(function () {
var params = { 'IDPaziente': 6586 }
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "GET", "url":"http://applicazioni.vsc300.it/Service.asmx/CercaPaziente",
"data": params,
"success": function (msg) {
var json = jQuery.parseJSON(msg.d);
//valorizza texbox
$("#TXT_CognomePaziente").val(json.Denominazione);
},
error: function (xhr, textStatus, error) {
alert(error);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="TXT_CognomePaziente" type="text" id="TXT_CognomePaziente" name="TXT_CognomePaziente" />
and this is the service:
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
Inherits System.Web.Services.WebService
' <WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, Method = "GET")>
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function CercaPaziente(IDPaziente As Integer) As String
Dim serialiser As JavaScriptSerializer = New JavaScriptSerializer()
Dim Paz As New CLS_Paziente
Paz.GetCercaAnagrafica(IDPaziente)
Dim serializer As JavaScriptSerializer = New JavaScriptSerializer()
Dim serializedItems As String = serializer.Serialize(Paz)
Return serializedItems
End Function
End Class
it returns an error, that Only Web services with a [ScriptService] attribute on the class definition can be called from script.
but i enabled it!!!
what can i do?
From this doc:
If more than one attribute is applied to a single program element, the attributes are enclosed in a single set of angle brackets and delimited from one another by a comma. For example:
<Obsolete(), WebMethod()>
Public Function PageCount(strURL As String) As Integer
(This was hard to find, by the way. I couldn't find it anywhere on MSDN.) So, this isn't what your code does, and the .NET compiler is probably ignoring your attributes altogether. Try this and see if it works:
<System.Web.Script.Services.ScriptService(), _
WebService(Namespace:="http://tempuri.org/"), _
WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1), _
Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Public Class Service
Inherits System.Web.Services.WebService

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.

serializing a json response using web service

As I'm new to knockout, web services and all this things, I'm trying to populate a dropdownlist using knockout js and a web service.
the Html code is
<body>
<select data-bind="options: printers"></select>
</body>
and the javascript block is
<script>
$(document).ready(function () {
var viewModel = {
printer: ko.observable(),
printers: ko.observableArray()
}
$.ajax({
type: "POST",
contentType: "application/json",
url: "PapersDDLs.asmx/getPrinters1",
data: "{}",
dataType: "json",
success: function (response) {
viewModel.printers(response.d);
}
});
ko.applyBindings(viewModel);
});
</script>
the web service I call is
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.Specialized
Imports System.Web.Script.Serialization
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class PapersDDLs
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function getPrinters1() As String
Dim db As New DataClassesDataContext
Dim printers = From p In db.Printers Select p
Dim values As New List(Of PrinterItem)
For Each pr In printers
values.Add(New PrinterItem(pr.BrandModelName, pr.Id.ToString()))
Next
db.Dispose()
Return New JavaScriptSerializer().Serialize(values)
End Function
End Class
The problem is that the string that is returned is made character by character.
Any help will be valuable
Thanks!
The function in your web service is slightly incorrect. You don't need to do the Javascript serialization yourself. Because you have marked the web service as a System.Web.Script.Services.ScriptService, the content of the response will automatically be serialized as JSON.
The method signature should be:
Public Function getPrinters1() As List(Of PrinterItem)
and the return statement should be:
Return values

Can you help me to find out why my $.ajax call to HelloWorld webservice fails here?

I am trying my best but cannot figure out why I do not get a sucesful response to such a simple web service; can you have a look at it tell me what do I miss, pls?
Each time only the error function is called and Fiddler says I have HTTP Response 500.
thanks!
Additional Notes:
I checked Fiddler and it says:
No web service found at: /JQuery-Recepie/Chapter16-Ajax/MyWebService.asmx. But WHY?!?
My WebService class:
[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 MyWebService : System.Web.Services.WebService {
public MyWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
My JavaScript that is bound to a button's click event which calls the webservice:
function jqHelloCall(){
$.ajax({ type: "POST",
contentType: "application/json; charset=utf-8",
url: "MyWebService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg){
alert(msg==null);
alert(msg.d);
},
error: function(){
alert('error');
}
}); }
Use the Firebug in Firefox to see the response sent by IIS. In Firebug on the Net tab you can filter only the Ajax requests (XHR). Most certainly you will find all the details about server exception in the response body IIS will send back.
pencilCake : I checked Fiddler and it says: No web service found at: /JQuery-Recepie/Chapter16-Ajax/MyWebService.asmx. But WHY?!?
Because the web methods should be STATIC
[WebMethod]
public static string HelloWorld() {
return "Hello World";
}
add the scriptMethod attribute to your service method...
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
return "Hello World";
}

Sending a complex object as parameter to Asp.Net PageMethod

I am trying to send an object created in JavaScript to an ASP.NET PageMethod. This object mirrors the properties of an existing custom business object, so i was hoping that i could pass a single object instead of a parameter for each property. I am getting an error "Unknown web method SavePart when attempting to use this method.
Javascript:
function() {
var pt = { Id: 1, Onhand: 20, LowPoint: 30, __type: 'Custom.Objects.Part'};
$.ajax({
type: 'POST',
url: 'partlist.aspx/SavePart',
data: JSON.stringify(pt),
contentType: 'application/json; charset: utf-8;'
dataType: 'json',
success: function(results) { alert('Success!'); }
});
}
Code Behind:
<WebMethod()> _
Public Shared Function SavePart(pt as Custom.Objects.Part) as Boolean
Dim repo as new PartRepository()
return repo.Save(pt)
End Function
I am using another PageMethod which just accepts an int, and this works fine.
I ended up solving my problem by sending the object this way through the jQuery ajax command:
data: '{"pt":' + JSON.stringify(pt) + '}'
this serialized the object automatically and returned it to my WebMethod. When i tried sending the object as is, i got an error saying "invalid JSON primitive".
You are attempting to pass a string to the method. You will need to accept the string, and deserialize it with fx. JavascriptSerializer or JSON.NET
I know this is incredibly old, but its not very intuitive when you're using this to figure out what the issues are. You are very close but I wanted to add a bit more to this in case someone else later wants to do the same thing. This works with nested objects as well, the one thing I can say is CASE matters in your JS variables that map to .NET POCOs on the page method.
Your "answer" is where I will start with. And as in the comments below it, yes you have to pass the object wrapped in its page method variable name.
Ill say it again, this is CASE-Sensitive, and can trip you up not just on the object's name but its properties as well. So to combat this I usually create my POCO object in .NET then copy that to the page so I know the names, capitalization and all are correct.
Something like this:
POCO:
Public Class CustomObject
Public Property Id as integer
Public Property ReqDate as DateTime
Public Property Message as string
End Sub
Now with a defined POCO for page method, replicate that "model" exactly as it is for the JS/AJAX to post with, being vigilant about case-sensitivity.
function ParseAndPostData()
{
var data = { custobj: {
Id: 1,
ReqDate: "04/12/2018",
Message:"Hello!"
}
};
//Stringify the data so it goes through page method parser
var postdata = JSON.stringify(data);
$.ajax({
type: 'POST',
url: '/BasePath/SomePage.aspx/SomeMethod',
data: postdata,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
var parsedACData = JSON.parse(msg.d);
alert(parsedACData);
},
error: function (msg) {
alert(msg);
}
});
}
Page Method (Note custobj in the parameters):
<WebMethod()> _
Public Shared Function PostCustomObject(custobj as CustomObject) as String
return custobj.Message
End Function

Resources