0

I have an array built as follows:

array sites=[
{'url':'cnn.com', 'description':'this is a news site','language':'english'},
{'url':'foxnews.com', 'description':'this is another news site','language':'english'},
{'url':'lemonde.com', 'description':'this is a french site','language':'french'},
]

I will be sending these values to my C# with jquery $.ajax, i.e.

    $.ajax({ type: "POST",
    url: "dbinsert.aspx",
    data: {
        url: urlvar,
        description: descvar,
        language: langvar
    }
 })

in my code-behind, I will then execute an sql statement creating all the rows and inserting the values.

I figure I should create a for loop to put all the urls together, and then all the descriptions together, etc, and then send them over, but how would my C# be able to tell the various values apart? I'm not sure what the most efficient way is to go about this...

Thanks in advance!

Phil
  • 159
  • 5
  • Can't you just make a JSON string from all the values and send that to the dbinsert.aspx? – user254875486 Apr 01 '12 at 15:59
  • @Lex, I don't mind trying anything, but I dont really have any experience with json, I wouldnt know how to create the json string from my array, and how to then deconstruct it serverside... – Phil Apr 01 '12 at 16:13
  • another kind of efficiency if you are going to have millions of items on your DB is to shorten stuff. example: english = 1, french = 2 then every time you display you transform the 1s and 2s with their respective languages – ajax333221 Apr 01 '12 at 17:06

2 Answers2

2

Phil, I'll do my best to help you take this start to finish.

First, in your page, declare a static method with the WebMethodAttribute decorator. The method must be static in order to be invoked from an AJAX call. This method will accept the asynchronous request and the data payload you send:

[WebMethod]
public static void DoWork(Dictionary<string, object>[] sites)
{
    using (MyDataContext db = new MyDataContext()) {
        foreach (var item in sites) {
            db.MyItems.InsertOnSubmit(new MyItem {
                Url = item("url"),
                Description = item("description"),
                Language = item("language")
            });
            db.SubmitChanges();
        }
    }
}

In here you can do your work to insert each item into the database, or whatever operation it is you intend to do. If you'd like, your method could even return a value that would be handled by a success callback function provided as an option to the jQuery $.ajax() method.

To consume this method using AJAX requires a few very specific parameters to jQuery. These constraints are unique to the way ASP.NET handles AJAX requests, so this would not be true of a call for something like PHP, ColdFusion, etc:

  • The method type should always be a POST.
  • Your expected return type should be specified as json.
  • The data option should always be a string value, not an object, so that is why we make a call to JSON.stringify() to get the JSON string representation of an object.
  • If you are not passing parameters to the method, you should always provide an empty object's string representation, "{}".
  • Finally, the content type of the request should be set to application/json; charset=utf-8.

You can actually set all these as defaults in a call to $.ajaxSetup() if you have multiple page methods you would call in this way, but it could also be specified in the individual options to that AJAX call. For instance:

$.ajaxSetup({
    type: "POST",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

If you forget any of this stuff there's a great article at Encosia that, while old, is still a handy reference tool for the current process for consuming page methods using jQuery, including all of these guidelines.

To make a call to the web method, you would provide the URL for the page followed by a forward slash and the name of your method, for instance (and I've included an example of setting all of those parameters in the individual call rather than in the setup function):

$.ajax({
    type: "POST",
    data: JSON.stringify({sites: sites}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "dbinsert.aspx/DoWork",
    success: function () {
         alert("Database insert complete.");
    }
});

I notice that you seem to have created a separate page for the AJAX method called dbinsert.aspx. If you haven't and that is actually the page containing your JavaScript and user entry form, then please disregard this section, but if you have, please know that you can declare web methods directly on the same page with your entry form and script, and using the correct URL parameter to specify the web method name you want to invoke, call these functions in that fashion.

If you would like to have a single place where multiple pages use the same web method to perform an operation using AJAX calls, I'd recommend setting up a web service instead (.asmx file). You would call this web service in the same way using a URL of myservice.asmx/DoWork, but you would not have to declare those methods static. There is also a ScriptServiceAttribute decorator created by Visual Studio's default web service template that is commented out initially. You would have to uncomment that line in order to call that service using jQuery, but those are the only two differences between the processes.

lsuarez
  • 4,952
  • 1
  • 29
  • 51
-1

Assuming you have can serialize and deserialize the JSON on the server and client, you can send the whole object (you'd have to change this, since it is an array now and I am not sure you can stringify an array) as one data item:

$.ajax({
    type: "POST",
    url: "dbinsert.aspx",
    data: JSON.stringify({'sites':sites})
});

Edit: After looking at the documentation, I think you can leave sites as an array. Edit2: Here is some information on how to parse the json on the server. Google can give you plenty more resources if needed.

Community
  • 1
  • 1
jbabey
  • 45,965
  • 12
  • 71
  • 94
  • You can definitely stringify an array without issue. I'd suggest exactly what you've done here, with the caveat that the `[WebMethod]` in your page should accept `Dictionary[] sites`. From there you can create a for each loop to iterate over the collection that would access each object's properties with code like `string myUrl = item["url"]`. Just keep in mind IE7 doesn't have the JSON object implemented natively and you'd need to import [the JSON library](https://github.com/douglascrockford/JSON-js) if you wish to support that browser and utilize the JSON library. – lsuarez Apr 01 '12 at 16:40
  • There is one thing, however. Your data object needs to be an associative array to identify the parameter name that the object is intended for. Your data option should read: `data: JSON.stringify({sites: sites})`. – lsuarez Apr 01 '12 at 16:50
  • jbabey and @lthibodeaux: as per your posts, stringifying and sending over my array was indeed easy. But I'm having trouble getting the data out. I tried deserializing the data as per [link](http://procbits.com/2011/04/21/quick-json-serializationdeserialization-in-c/) like so: protected void Page_Load etc { var c = HttpContext.Current; var jst = c.Request["sites"]; var jss = new JavaScriptSerializer(); var dict = jss.Deserialize>(jst); string row=dict[0]['url']); but on this last line I get "the best overloaded method match...has some invalid arguments... – Phil Apr 01 '12 at 18:08