WebMethod not working in ASP.Net Web Role (Web Forms)? - javascript

Repro:
Open VS2013, File > New "Azure Cloud Service" Project > Add an "ASP.NET Web Role" (named as WebRole1)
Select "Web Forms" template for the web role.
Add jquery-1.11.1.min.js and a new WebForm1.aspx to the WebRole1 Project.
Add the following code to the of WebForm1.aspx
<script src="jquery-1.11.1.min.js"></script>
<script>
$(function() {
$.ajax({
type: "POST",
url: "WebForm1.aspx/Foo",
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{a: 'webmethod!'}",
success: function(data) {
alert(data.d);
},
error: function() {
alert("error");
}
});
});
Add the following function to the WebForm1 class in WebForm1.aspx.cs
[WebMethod()]
public static string Foo(string a)
{
return a;
}
Set WebRole1 project as Startup Project and run. The browser alerts "undefined".
But you can get "webmethod!" using plain ASP.NET WebForm project. What is wrong?
I noticed that in url: "WebForm1.aspx/Foo": if you change the aspx part, the ajax fails; if you change the Foo part to whatever value, the ajax always succeed. This is unusual! In plain ASP.NET Web Form application, changing either part will result in "error"!
If you create an Empty ASP.NET Web Role, the ajax will succeed!!! What is going on?

JavaScriptSerializer is pretty flexible, but it might be worth trying valid JSON in the data parameter, like:
data: '{"a": "webmethod!"}'
I believe JSS will handle keys/values in single quotes, even though that's not technically valid JSON, but the unquoted a might be a bit much.

Related

Opening new page passing parameters without showing them on the URL

I'm making a MVC C# Web App, and I began wondering whether you could open other pages that need parameters to function, without actually sending them through the URL, which is unsafe, and can lead to some user messing up another registry of the database.
My issue is though, I've never done such a thing, and I cannot find any example of code that does such a thing. The project is run with C# and JS, and the main things I've tried include:
-Doing so with Ajax:
First of all I have a button that calls for a function:
Link Text|
function openHorario(id, id_schedule, id_tool) {
alert(oid, id_schedule, id_tool);
$.ajax({
type: 'POST',
url: '/Schedules/actionEditStuff',
data: {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
},
async: 'false',
success: function (data) {
//???
}
});
}
I know there's a way to go to a new page with the success Ajax return, but... That also requires for you to send the parameters through URL.
Obviously, that didn't work, because what the action does in the controller is to return a view, not a page. So... I realized that my idea was not very smart, and moved onto somewhere else: Link, but those always end up having to send the parameters visibly through URL.
Is there any way at all to do this in a proper, clean manner?
Thank you!
#Layan - just to illustrate my comment above, - you could implement something along these lines:
your client side invokes via ajax
...
var data = {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
};
$.ajax({
url: '/Schedules/actionEditStuff',
type: "POST",
data: data,
contentType: 'application/json; charset=utf-8',
success: function (view) {
//load returned data into div? or popup?
}
, error: function (xhr, status, error) {
...
}
});
...
and your controller action
public ActionResult actionEditStuff(....parameters...)
{
...
...do your magic ...
return PartialView("~/Views/_PartialViewThatShowsSomething.cshtml", ...pass model...);
}

Data at the root level is invalid on $.ajax call

I have a simple web service that I am trying to utilize. Obviously, this will be more enahnced down the road but am trying to grasp the basic concept of the ajax call.
Web Service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace Tools
{
/// <summary>
/// Summary description for CFServices1
/// </summary>
[WebService(Namespace = "http://localhost:51342/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 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 CFServices1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hellow World";
}
}
}
JavaScript
$.ajax({
type: "POST",
url: "CFServices.asmx?/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (response) {
console.log(response);
}
});
The ajax call appears to work fine as it returns an error:
"<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
--- End of inner exception stack trace ---</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>"
I have tried a couple different things that lead me down the path of the URL property being invalid but since I'm getting an actual response, I'm assuming it's correct. It definitely renders if I navigate to it through a browser. Even if I try and invoke the web service through the asmx page, it all works.
I have tried changing the data type to be plain text but that doesn't work either. Since all the web method does is reutnr the string 'Hellow World', I shouldn't need to pass any arguments but tried passing blank values just in case. Everything either brings me back to the response returning 'undefined', the html markup for the asmx page or this. The 'data at the root element is invalid.' This tells me that either the data being sent to, or recieved from the web service is incorrect or doesn't have the right formatting. This is where I'm getting hung up at because I can't figure out what could possibly be wrong here.
Although this is something probably simple, I'm not finding any luck whatsoever on SOF or other threads. Any helpful insight is greatly appreciated.
As we are calling it from jquery ie., from script part you need to make the below changes to Webservice part,
[System.Web.Script.Services.ScriptService] // Mark it for accessing from script
public class CFServices1 : System.Web.Services.WebService
We need to set script method attribute for the web method as below
[WebMethod]
[ScriptMethod]
public string HelloWorld()
Then while calling it from ajax call just remove ? in url part as below,
$.ajax({
type: "POST",
url: "CFServices.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (response) {
console.log(response);
}});
Hope it helps.
I had everything thilsiva suggested but was still receiving this error. It worked on my local development machine but not when deployed. The problem was I was getting my URL from the config file and I was accidentally missing the method name in my deployed version. So make sure you have the method name included if you're in the same situation.
url: "CFServices.asmx/HelloWorld",
not
url: "CFServices.asmx",

ASP.Net web service always return XML not JSON

Currenly i use asp.net web service but when i call web service method by ajax call it always return XML not json
i try
ASP.Net web service won't return JSON - Always XML
but its also not work for me..
JS :-
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "http://www.quietincomes.com/LoginWebservice.asmx/Demo",
dataType: "jsonp",
success: function (data) {
alert("1" + data);
},
error: function (result) {
alert("2" + JSON.stringify(result));
}
});
LoginWebservice.asmx :-
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Demo()
{
return "Harshit";
}
where i am wrong..
jsfiddle Example:-
http://jsfiddle.net/EXvqc/
First you have to use Post method to send a request to your web service. And as you have used JSONP as it always looks for the callbacks, and you have to define callback methods for it.
Please Refer
And the other thing you have to add like following
[System.Web.Script.Services.ScriptService]
// 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 LoginWebservice : System.Web.Services.WebService
{
[WebMethod]
public string Demo()
{
return "Harshit";
}
}
Indicates that a Web service can be invoked from script. This class cannot be inherited.
Your aspx/HTML will contain
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "http://www.quietincomes.com/LoginWebservice.asmx/Demo",
dataType: "json",
success: function (data) {
alert("1" + data);
},
error: function (result) {
alert("2" + JSON.stringify(result));
}
});
See output below
JSONP is not JSON, JSONP is used to get over the same origin policy (site A cannot make ajax request to site B). To solve this problem site A will create a script tag:
document.createElement("script")
Then set it's source to site B, usually specifying a callback like www.B?callback=callMe
A typical response of site B would be:
callMe({siteBSays:"hello"});
JQuery hides creating the javascript element for you so it looks like a normal ajax request. Make sure site B has the right response type headers I think it's text/javascript
Another way to do cross domain requests is that site B has a response header that allows site A making ajax requests to it (cors) by setting a response header Access-Control-Allow-Origin

Consuming web service in HTML

I have created a web service and saved its .wsdl file. I want to consume this service in my HTML file by providing its URL.
Can anybody tell me how to call the URL in HTML and use it?
Like its done here.
http://www.codeproject.com/Articles/14610/Calling-Web-Services-from-HTML-Pages-using-JavaScr/
The only difference is my web service does not have an extention like "asmx?wsdl".
Does that makes any difference.
I followed that tutorial too but it does not produce any output.
Thank You////
You definitly should get familiar with AJAX.
You could use the ajax functionalities provided by jQuery. That's the easiest way, I assume. Take a look at http://api.jquery.com/jQuery.ajax/
You can use this like
$.ajax({
url: "urltoyourservice.xml"
dataType: "xml",
}).done(function(data) {
console.log(data);
});
HTML itself cannot consume a webservice. Javascript ist definitely needed.
The existence of your WSDL File looks like you are probably using a XML format as the return of the web service. You have to deal with XML in javascript. Therefore take a look at Tim Downs explanation.
But keep in mind, that your web service URL must be available under the same domain as your consumption HTML-File. Otherwise you'll receive a cross-site-scripting error.
yes you can use ajax but keep in mind you wont be able to make a request across domains. Consuming web services should be done in server side.
To further gain more knowledge about this, read How do I call a web service from javascript
function submit_form(){
var username=$("#username").val();
var password=$("#password").val();
var data = { loginName: username, password:password };
$.ajax( {
type: "POST",
url:"Paste ur service address here",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
var value = data.d;
if(value.UserID != 0){
alert.html('success');
}
},
error: function (e) {
}
});
}
Try this it will help

Calling c# events from javascript code

Could you please tell me if I can call a C# event or method from javascript code in an ASP.NET web application?
You cannot directly execute a C# Event or Method. You can hit an endpoint via AJAX. This could be an ASP.NET MVC Controller or an .ashx handler.
Alternatively you can look at implementing something like SignalR, which via its Hubs, allows you to do magical things from javascript (and from the server, push notifications and things of that sort.)
You can't. C# is executed in the server side while javascript is execute in client side (browser).
As I have pointed previously:
Example using Page methods: http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
http://sappidireddy.wordpress.com/2008/03/31/how-to-call-server-side-function-from-client-side-code-using-pagemethods-in-aspnet-ajax/
Example using AJAX:
http://www.codeproject.com/Articles/250582/Getting-Started-with-jqChart-HTML5-jQuery-Chart-Pl
Yes one can call C# Method from javascript using ajax in asp.net webforms also can do that in asp.net MVC
for example here is web forms example
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
</script>
and new code behind c# method
[WebMethod]
public static string GetData()
{
return "This string is from Code behind";
}
Output looks like this

Categories

Resources