In researching this problem most SO issues were about the static method as a fix.
Since it's not working with the real (and a bit sophisticated) WebMethod I've just created a simple one for the sake of checking if reaching the method itself is possible.
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static string HelloWorld()
{
return "Hello World!";
}
The call.
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "usersWebMethods.aspx/HelloWorld",
dataType: "json",
success: function (data) {
alert(data.d);
}
});
});
</script>
It always comes down to 500 (Internal Server Error)
Unknown web method HelloWorld.
Parameter name: methodName
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unknown web method HelloWorld.
Parameter name: methodName
Why is this failing?
I had this issue as well, but slightly differently I had this method in a .asmx file and so ran across the "static" issue, but in a different way.
If you have a method as part of your Page class, it must be static.
If you've put a method in an .asmx file to use across several pages, it must not be static.
I had a problem in the actual .aspx file, the line
<%# Page Language="C#"
AutoEventWireup="true"
CodeBehind="xxx.xxx.cs" Inherits="xxx.xxx" %>
wasn't present in the code. How did it get changed? I Don't know :(.
For me, the primary issues was to change javascript post to pass in no arguments such as
$http.post("Status.aspx/MyData", {})
Then to verify nothing was cached, I then deleted [System.Web.Services.WebMethod] in the code behind file above public static string MyData(). Then I built the project to failure, then re-added the aformentioned deleted attribute and built to success.
Upon running it worked.
Missing the [WebMethod] above your server side function will also cause this error.
To be honest, I've just realised "again" how tired we could be in some cases.
For me it was just a private method instead of a public one.
In my case there was a problem in the URL, it was a Asp.Net Website application:
For ex:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "usersWebMethods.aspx/HelloWorld", <----- Here
dataType: "json",
success: function (data) {
alert(data.d);
}
});
My usersWebMethods.aspx in inside UI (Custom Created) folder so If I put URL as usersWebMethods.aspx/HelloWorld it does not work but when I added leading / to it then ajax method called properly!
Changed from:
usersWebMethods.aspx/HelloWorld
To
/usersWebMethods.aspx/HelloWorld --
I run into this exact problem in ASP.net(framework/web forms) with JS using webservice and I solved it by removing the static key word from the method declaration
[WebMethod]
public List<ViewModel> GetAirLines()
{
//Code goes here
}
instead of
[WebMethod]
public static List<ViewModel> GetAirLines()
{
//Code goes here
}
Related
I have a C# .NET MVC 5 project. I'm trying to submit a GET request from ajax to a controller method on the server. The problem is that, even though this jquery is being called, the GET always returns a 404. Here is the js:
var theArguments = { "prefix": prefix, "level": level, "number": number };
$.ajax({
url: "GetMasteryObjective",
type: "GET",
data: theArguments,
//data: JSON.stringify({ prefix: "prefix", level: "level", number: "number" }),
//url: "/MasteryObjectiveAPI/GetMasteryObjective?prefix=" + prefix + "&level=" + level + "&number=" + number,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Successfully queried the database to validate the given mastery objective.");
},
error: function () {
console.log("There was an error with trying to validate the mastery objective with the database.");
}
});
As you can see I've tried several variants of how the variables are submitted (commented out). This is the controller method that is never getting hit.
[HttpGet]
//[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static MasteryObjective GetMasteryObjective(String prefix, String level, String number)
{
//code here
}
Other methods in the same controller have no problem being posted to. So maybe there's something I don't understand about GET? I understand that it should be valid to submit variables with a GET request.
Wow. I just discovered the answer to my own question while creating this post. I needed to remove static from my controller method.
Happy that, you have got the solution.
However, thinking that this may help others .....
One of the reason for ajax call not hitting the Method in controller is:
If the controller method is under [Authorize] but the user is trying to hit without logging in.
Solution: If want to allow unauthorized access to that method; mark that method has [AllowAnonymous], otherwise log-in and then try.
I am currently creating a webpage in C# as a school project.
I have created a WebMethod in the file:
Default.aspx.cs
[WebMethod]
public static string MyWebMethod()
{
return string.Format("Hello From Server");
}
And the Ajax call in the file:
Default.aspx
<script type="text/javascript">
function test() {
jQuery.ajax({
type: "POST",
url: "Default.aspx/MyWebMethod",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(dd, status) {
alert('Success' + JSON.stringify(dd) + " status: " + JSON.stringify(status));
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
}
</script>
<input type="button" value="click me" onclick="test();" />
I have inserted a breakpoint at the start of the "MyWebMethod()", however when im debugging, the breakpoint never gets hit.
I have been sitting with this problem for about 4.5 hours now, trying every example I could find on google, and even if I download a complete example ie. "Default.aspx" and "Default.aspx.cs" files with "working" code, I cannt get it to run in my Solution.
Is there some setting you have to enable to be able to use JQuery, Ajax and WebMethods?
After I put the JSON.stringify(dd) I was able to get the error message:
json:{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
But after searching for a solution for several hours I have almost given up.
When I try a fix, which apparently have worked for other people with that error, it still doesn't work for me.
Does anyone know how to make this work?
Thanks for your time
You should change your url path of your jquery ajax:
url: "Default.aspx/MyWebMethod",
You do not need to add .aspx to it, only to the page.
Assuming that your method is defined in a Default.aspx file’s code-behind, located in a folder named "Views", then your url should be like this:
url: "/Views/Default.aspx/MyWebMethod",
comment out the AutoRedirectMode in Routeconfig of App_Start folder will solve this issue
// settings.AutoRedirectMode = RedirectMode.Permanent;
Does anyone know if it's possible to use jquery/ajax to call a c# (or any other .net) function in another project within the same solution?
Let's say that the solution's name is ExampleSolution , the name of the project from which I call the target function is Project.Source and the name of the target project is Project.Target,
and the name of the target function is TargetFunction().
I've tried following in an .js file in the Project.Source:
$.ajax({
url: '/ExampleSolution/Project.Target/TargetFunction',
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
Then I've modified the url-line in several ways but never succeed.
Do you have any advice?
Thank you all for your fast answers.
I found a solution for the problem and I'd like to share it just in case anybody faces the same problem in the future.
In the .js file before I call the $.ajax function I create a variable with help of window.location which points to the url to the targetfunction of the running target-project and use the variable in the ajax-function. So you don't point to another project. You point to url of running project.
Just as easy as it sounds.
Below follows the solution:
var url = window.location = 'http://localhost:13105/TargetFunction';
$.ajax({
url: url,
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
});
You can only call functions in the Code Behind because they're being registered by the web server.
If you want to have a function accessible outside the Code Behind it needs to be registered as a ASMX or WCF service.
See Creating and Consuming Your First WCF Service for setting up a WCF Service.
Once it is setup and running you can use Ajax to call the methods just like you would in the Code Behind.
$.ajax({
//Path to WCF Server and Target Method
url: "http://localhost:PORT/wcfsvc/FooService.svc/Foo",
type: 'get',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$(document.body).append(data);
}
});
See also: Consuming WCF from jQuery as JSON
The short answer is "No, it isn't possible." Front-end code (like jQuery and AJAX) run on the client's machine, but C# functions are back-end and run on the server. There's no direct connection between them.
The longer answer is "Not directly, but there are ways to do something similar." Your easiest option is to use AJAX to POST to another controller/action on your server and then process the response. This is close to what you were doing, but you were slightly off. Rather than the url being a function, the url has to be an actual url on your website. Using /Functions/CallTargetFunction as an example, you would then create a controller like this:
public class FunctionsController : Controller
{
public ActionResult CallTargetFunction()
{
return Content(TargetFunction());
}
}
Note that doing this means anyone who visits http://yoursite.com/Functions/CallTargetFunction will get the result of that function.
I tried all my efforts, but just can't understand where the error lies. I searched the google also but did not find any good solution. It is not actually calling the controller/action in mvc. The same is running good in the other parts of the project.
I have a contrller "RB" under a folder "MVC", the action is defined as "SS".
and I am firing following code from my javascript file :
var sSch = function (request, response) {
var t = request.RF.substring(0, 1);
var d = new Date(request.RNR);
$.ajax({
url: "/MVC/RB/SS",
type: "POST",
dataType: "json",
data: {
_rId: request.ReportId,
_date: d.toString(),
_fcy: t
},
success: function (data) {
alert('Success');
},
error: function (data) {
alert('Error');
}
});
};
I am calling this function onClick of a button and properly getting the values in Request variable, but it is not anyhow calling the Controller/Action there.
On firebug I tested it throws the exception "ReferenceError: url is not defined". I am using MVC3 under VS 2010.
Please Help.
You have to define your action properly instead of
url: "/MVC/RB/SS",
use
url: #Url.Action("SS", "RB")
For the url you have 'MVC/RB/SS' this is relative to your current directory a quick test would be to put in url: "../MVC/RB/SS" or url: "../../MVC/RB/SS" depending on how deep you page is in the site structure.
Another way would be to try this:
url: "#Action("/MVC/RB/SS")",
this will create the correct url at the correct level for you and should be picked up.
Try this:
url: "~/MVC/RB/SS",
This will resolve to path "http://site-name/MVC/RB/SS".
What does Firebug say?
I have an asp.net application with a static page method. I'm using the below codes to call the method and get its returned value.
$.ajax({
type: "POST",
url: "myPage/myMethod",
data: "{'parameter':'paramValue'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {alert(result);}
});
What i got returned is [object Object].
Below is my static method. And I also have EnablePageMethods="true" EnablePartialRendering="true" in my ScriptManager.
[WebMethod]
[ScriptMethod]
public static string myMethod(string parameter)
{
return "Result";
}
Is there a way for me to get the returned value?
Try using Chrome developer tools or the firebug plugin from Firfox. Not sure if IE's developer tools lets you inspect the ajax calls?
The resulting string you are looking for is actually within the result object. You need to look at the d variable. I remember reading somewhere why this was, I think it is ASP.NET playing around :|
Try:
success: function(data) {alert(data.d);}
c#
[WebMethod]
public static string GetTest(string var1)
{
return "Result";
}
Hope this helps.
Its just that you are stuck at the .d that is introduced in the JSON response from ASP.NET 3.5. To quote Dave Ward,
If you aren’t familiar with the “.d”
I’m referring to, it is simply a
security feature that Microsoft added
in ASP.NET 3.5’s version of ASP.NET
AJAX. By encapsulating the JSON
response within a parent object, the
framework helps protect against a
particularly nasty XSS vulnerability.
So just check whether .d exists and then unwrap it. Change your success function like this.
success: function(result) {
var msg = result.hasOwnProperty("d") ? result.d : result;
alert(msg );
}
What about this?
$.ajax({
type: "POST",
url: "myPage/myMethod?paramater=parameter",
success: function(result) {
alert(result);
}
});
I found out the solution.
You can use parseJSON to get the result
http://api.jquery.com/jQuery.parseJSON/
or change the datatype to html to see the actual value.
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
Thank you guys for your help.