I cannot get my WebMethod to work in ASP.NET - c#

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;

Related

Ajax call unsuccessful in Asp.net

After debugging my application, I found that ajax call is unsuccessful.
I have tried multiple solutions found on web but still I am unable to resolve this issue.
One solution which I found is to set
settings.AutoRedirectMode = RedirectMode.Off;
line in RouteConfig.cs but my RouteConfig.cs file does not contain this.
This is the code in RouteConfig.cs file.
I also tried this but still it made no difference
url: '<%= ResolveUrl("UploadProduct.aspx/SaveData") %>',
Code of Ajax call.
This is the Web method
$.ajax({
url: "/Controller/ActionMethod/",
method: "POST",
data: {empdata: data}
});

Why is this jquery ajax GET call to a C# method not working?

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.

Unknown web method. Parameter name: methodName

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
}

Jquery call to Controller of MVC: ReferenceError: url is not defined

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?

Calling a function in the .aspx.cs code behind file with jQuery load()

So I have something like this situation:
$(document).on('click', 'a[data-link]', function () {
var $this = $(this);
url = $this.data('link');
$("#imagePreview").load("imageProcess.aspx?" + url);
where url holds GET parameters. But imageProcess.aspx is different than the file I'm in (dashboard.aspx) and I need to reference some panels within my dashboard.aspx file. So my question is, using the .load() function, or even any function that could get the job done, how do I call a function, with GET parameters, in the dashboard.aspx code behind file? I'm fairly new to the .NET framework so I apologize if the question sounds elementary.
In your imageProcess.aspx.cs create a webmethod like:
[WebMethod]
public static string YourMethod(your parameters)
{
//Do Your Work
}
and in your dashboard page, in javascript use jquery to send request your webmethod like:
$.ajax({
type: "POST",
url: "imageProcess.aspx/YourMethod",
data: "{parameter1Name:'" + JSON.stringify(parameter1value) + "', Parameter2Name:'" + JSON.stringify(parmeter2Value) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// do your success work, keep in mind that your returned data will be in data.d
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// do your failuer work
}
});
I hope it will give you a guidance to achieve your task.
Just to make sure: You are trying to access functionality from a different aspx page than the one you are currently on.
I'm not entirely sure if you can do that the easy way by java script. Maybe someone else knows a better way, but the way I would do it is creating ashx service page which will handle your request so you can provide the data you need (in your case an image)
For more information see http://www.dotnetperls.com/ashx

Categories

Resources