jquery ajax call return value - c#

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.

Related

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.

Call code-behind function from javascript in visual webpart

Is it even possible? To call a code-behind c# function from javascript in a visual web part?
It is a complex function so converting all my codes to client side is not an option. I want the logic that is there in this function to happen without a page refresh. This is the background of my issue.
Thanks guys..
You can use jQuery ajax to call server side method and get the response to be used in javascript. This article has simple and good example to show what you need to do.
Code behind
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Javascript
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Why don`t you use a Webservice (Ajax-Enabled WCF Service) which can be called via AJAX?
I think this would be the clean way. Put your logic in an extra class and use this class in the webservice and your webpart. Then you cann call the Method from Code and from Javascript.

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