Ebikeneser
Ebikeneser

Reputation: 2364

Return C# List<string> using ajax

I have the following list -

public static List<string> dataNodes;

Then I want to be able to access it by using ajax -

      $.ajax({
                type: "POST",
                url: "Default.aspx/dataNodes",
                success: function (data) {
                    alert(data.d);
                },
                error: function () {
                    alert("error");
                }
            });

However every time I do this data.d is undefined, is there a way to do this?

Upvotes: 0

Views: 5548

Answers (3)

Jon Jay Obermark
Jon Jay Obermark

Reputation: 365

I suggest that if you are already encased in something as heavy as dotNet, you should use its internal power

  • Make an <input type="hidden" runat="server" ...> object (or its <asp:...> equivalent)
  • have the page code keep its value up-to-date, and then
  • get the value out of that "hidden" in your JavaScript.

If you need to control when the value gets updated use:

  • __doPostback(), or
  • ClientScriptManager.GetPostBackEventReference.

Those wrappers let dotNet write the JavaScript that calls an event handler that will update the variable for you. That code will be more able to avoid running afoul of other dotNet functionality on the same page.

Adding two post-back mechanisms to the same page is asking for weird interactions that will be hard to debug, especially since you seem to misunderstand ajax in a fundamental way.


Ajax submits the entire page to your code and returns the output. So unless you have a path through your page code that notices the marker on the query string and outputs the stringified value of the variable, this will not work.

Put a breakpoint in Page_Load and you will see the ajax calls back into your page as though it were preparing another copy of the entire page.

You have the option at that point of noticing the decoration that indicates this is AJAX, diverting the page preparation and writing your variable contents to the Response, and then skipping further processing.

It is better to prepare an entirely different URL for Ajax to use, in which case you should use WebServices as noted by an earlier respondent.

But, again. There is a way to do this entirely in dotNet, and it is already using these mechanisms. So your attempts to use the same ones can become very hard to debug when they go wrong.

So I would either avoid Ajax, or avoid dotNet, on any given page.

Upvotes: 0

Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61479

Here's an example for you to start.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public List<string> GetDataNodes()
{
  var dataNodes = new List<string>{ "aaa", "bbbb"};
  return dataNodes;
}

Then change Javascript to

$.ajax({
    type: "GET",
    url: "Default.asmx/GetDataNodes",
    success: function (data) {
        alert(data[0]);
    },
    error: function () {
         alert("error");
    }
});

Change your .aspx to .asmx (service) and and that should do it.

Upvotes: 1

xDaevax
xDaevax

Reputation: 2022

For many reasons, security being a big one, you wouldn't want an Ajax call to be able to access your server-side properties and fields directly (as anyone with knowledge of your code could do this). This is why you would want to create a public-facing API when you want to expose a piece of data via Ajax, you'll need to serialize the data on the server and expose it via some request in order to consume it with Ajax. A common way to achieve this is using WebMethod attributes.

The quickest way to expose something like this, would be to set up one of these WebMethods in your code-behind like so:

[WebMethod]
public static string getStringData() {
    JavascriptSerializer ser = new JavascriptSerializer();
    return ser.Serialize(dataNodes);    
}

Here is a good resource for this style: http://aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

Then your Ajax URL becomes Default.aspx/getStringData

That being said, it seems to me that if you're exposing data like this, you may want to consider setting up a REST-full web service or some kind of service that exposes data instead of having your code-behind handle this. As others have said as well, this should be a GET operation, not a POST.

For some great examples of getting a web service setup to expose this kind of data, here are some helpful articles:

Upvotes: 0

Related Questions