10

I'm a bit new to C# and javascript so while my question is specific I am open to any alternatives.

I have an array of values (that I have created in a javascript function) that I want to send to my code-behind file to be used in a method. From what I've researched using ajax and stringifying the array with JSON seems like the best method.

My questions are

  1. Can I pass the array using this method?

  2. How do I capture the information on the server side(in my code-behind?)

Javascript passing the values

var jsonvalues = JSON.stringify(values);
var callback = window.location.href
$.ajax({
  url: callback
  type: "POST",
  contentType: 'application/json',
  data: jsonvalues
});

I've seen many solutions using [WebMethod] or some kind of WebService to capture the data, can I use this to do work in my code-behind file without having to return data?

Here is what I'm using on my code-behind file

[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
}
David East
  • 31,526
  • 6
  • 67
  • 82
Matt Foxx Duncan
  • 2,074
  • 3
  • 23
  • 38
  • Thanks! After fleshing out my question it's become clear that this is a crucial component. I'm going to try and use Milimetric's answer using `[HttpPost]` first though. – Matt Foxx Duncan Jun 20 '12 at 16:16
  • I still don't know how to handle the call on the code-behind side. I tried writing a method to capture the array but I keep getting an error with the ajax call. I've added my code-behind method to the original question – Matt Foxx Duncan Jun 20 '12 at 17:51
  • Take a look at this question [Jquery AJAX with ASP.NET WebMethod Returning Entire Page](http://stackoverflow.com/questions/348689/jquery-ajax-with-asp-net-webmethod-returning-entire-page). Ignore the part about returning stuff and look at how they are constructing the `url`. – Roman Jun 20 '12 at 18:48
  • Thanks for the link, I got the call to post properly -- I am receiving `success` back from the call. However my method is still not being invoked. – Matt Foxx Duncan Jun 20 '12 at 19:02
  • Edit time ran out on last comment... Two possible reasons I've come up with... 1) My code-behind uses a `partial class` and inherits the base class `System.Web.UI.UserControl` rather than `Page`(as I've seen most [WebMethod] example use). The UserControl base class is necessary for other methods in the class, do I *need* to have my WebMethod inherit `Page`? 2) I'm not use `` or PageMethods, do I need these? – Matt Foxx Duncan Jun 20 '12 at 19:10
  • Well it looks like I can't send javascript to a user control. I've been on a wild goose chase all day. Great. – Matt Foxx Duncan Jun 20 '12 at 19:27
  • I have a break set in the several methods(including the [webmethod] and am using debug, if it was being called it would break. Now that I know I've also seen [multiple posts](http://stackoverflow.com/questions/5638184/call-webmethod-in-user-control) on stackoverflow about the same question, the answer always being that it can't be called that way. I'm attempting to add the values to a querystring which I can then use `Request.Params[values]` on in the user control as a workaround. – Matt Foxx Duncan Jun 20 '12 at 19:55

3 Answers3

8

I have written a in-depth example for this using ASP.NET MVC, but it can easily be adapted for WebForms.

Send data with jquery to an MVC controller

The HTML and jQuery will look almost exactly the same, with the exception of where you call the WebMethod.

If the page you are using is called Default.aspx, and the method is called Done, then your URL for the WebMethod will be Default.aspx/Done.

<script>
       // Grab the information 
       var values = {"1,","2","3"};
       var theIds = JSON.stringify(values);

       // Make the ajax call
       $.ajax({
         type: "POST",
         url: "Default.aspx/Done", // the method we are calling
         contentType: "application/json; charset=utf-8",
         data: {ids: theIds },
         dataType: "json",
         success: function (result) {
             alert('Yay! It worked!');               
         },
         error: function (result) {
             alert('Oh no :(');
         }
     });
  </script>

Your WebMethod will still be the same.

[WebMethod]
public static void done(string[] ids)
{
   String[] a = ids;
   // Do whatever processing you want
   // However, you cannot access server controls
   // in a static web method.
}
Community
  • 1
  • 1
David East
  • 31,526
  • 6
  • 67
  • 82
0

The easiest way is to use ASP.NET MVC and data bind to a list. So for a list of strings, this would be very easy. Just make a controller action that looks like this:

[HttpPost]
public ActionResult MyAction(string[] values)
{
    ... debug and see that values gets set to your array from javascript ...
}

and then pass data: values in your $.ajax call. There's no need to stringify, jQuery will figure out what to do. For more complicated list bindings, check this out (and many other resources like it talking about fancy ways to bind to complex object lists):

http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

For calling [WebMethod] methods from web pages or web services, check out this guide:

http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Basically though you need the url to be ServicePage.aspx/MethodName

Milimetric
  • 13,411
  • 4
  • 44
  • 56
  • Do I still need to specify the contenttype in the `$.ajax` call then? Should I use `processData:false` for the call? – Matt Foxx Duncan Jun 20 '12 at 16:15
  • I usually bind strongly typed stuff so I set up forms and post those. In my case, I don't even need to use $.ajax, I just use $.post. Here's the best advice I can give you. Set it up how you have and put a breakpoint in the controller action I showed above. Then, look at the Request object and see what parameters are being passed in. Basically, you'd want a parameter called "values" to have a comma separated list. You can then tailor your jQuery to exactly what you need. – Milimetric Jun 20 '12 at 16:31
  • Thanks for all your help! However I have just discovered the platform I am building on (Sitecore) does not yet support MVC(a release that does will be out at the end of this month) I am trying to use `[WebMethod]` as mentioned by @R0MANARMY in lieu of this but cannot get my `ajax` call to trigger the method I've written. I have modified the ajax call to say `url:'Register/trigger'` where trigger is the method in my callback. Am I missing something? Again, thanks for all the help! – Matt Foxx Duncan Jun 20 '12 at 17:20
  • I'll edit my answer with this, but I think you need something like `url: 'Register.aspx/trigger'` if you're using a page or `.asmx` if you're using an old fashioned service. Check this out for more info: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/ – Milimetric Jun 20 '12 at 20:48
-1

Put your data in a hidden field with runat=server. Post the form and fetch the data normally.

Søren Lorentzen
  • 868
  • 1
  • 11
  • 26