SHeinema
SHeinema

Reputation: 634

Javascript processing server-side data in ASP.NET

I have a program which gets a list of locations from an sql db via a linq-to-entities query in a c# code-behind. This list needs to be parsed by a javascript method (Google maps api v3) in order to display the locations on a map. I need to find the best way to get the info from the server-side query to the javascript function for processing. Any thoughts!?

Edit: error on serialization...

JavaScriptSerializer jss = new JavaScriptSerializer();
            using (RamRideOpsEntities myEntities = new RamRideOpsEntities())
            {
                var validDates = (from a in myEntities.AdminOptions
                                  select new { a.ValidDate1, a.ValidDate2 }).First();

                var allWaitingRides = (from r in myEntities.Rides
                                       where ((r.TimeOfCall >= validDates.ValidDate1 ||
                                            r.TimeOfCall <= validDates.ValidDate2) && r.Status.Equals("Waiting", StringComparison.OrdinalIgnoreCase))
                                       orderby r.TimeOfCall descending
                                       select r).ToList();

                json_topTen.Value = jss.Serialize(allWaitingRides.GetRange(0, 10).ToArray());
            }

Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.

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: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.

Source Error: 


Line 106:                                       select r).ToList();
Line 107:
Line 108:                json_topTen.Value = jss.Serialize(allWaitingRides.GetRange(0, 10).ToArray());
Line 109:            }
Line 110:        }

Source File: D:\DOCUMENTS\RamRide\RamRideOps_PL\RamRideOps\RamRideOps\Ops\DispatchCar.aspx.cs    Line: 108 

Stack Trace: 


[ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.]
   System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
   System.Collections.Generic.List`1.GetRange(Int32 index, Int32 count) +70
   RamRideOps.DispatchCar.setTopTen() in D:\DOCUMENTS\RamRide\RamRideOps_PL\RamRideOps\RamRideOps\Ops\DispatchCar.aspx.cs:108
   RamRideOps.DispatchCar.Page_Load(Object sender, EventArgs e) in D:\DOCUMENTS\RamRide\RamRideOps_PL\RamRideOps\RamRideOps\Ops\DispatchCar.aspx.cs:41
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +91
   System.Web.UI.Control.LoadRecursive() +74
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272

Upvotes: 1

Views: 1375

Answers (3)

bbqchickenrobot
bbqchickenrobot

Reputation: 3709

If you're using asp.net mvc then you can return JSON back to the client using a javascript/jquery call. Here is a tip on how this can be done from one of the big experts on MVC (Phil Haack): Callng MVC from Javascript

If you're using standard asp.net you could use web methods or asmx pages to return your JSON data.

Make the call w/ linq to entities in either of the above then convert to json and pass it on down...

Looks like you're using standard asp.net (non mvc) - check out this tutorial:

ASP.NET Web Methods & jquery

Upvotes: 3

doogle
doogle

Reputation: 3406

If your entities are light enough, just serialize them into a JSON array and pass that back to the client. If they aren't very light, create some data transfer objects to get the job done.

Here is what your ajax request could look like (using jQuery):

$.ajax({url: "url/to/handler.ashx",
    success: function(data, state) {
        //data represents the array of objects sent back from the server.
    }
});

Your handler would behave as specified below:

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/x-javascript";
        //fetch data from database.
        //return data by writing the serialized objects directly to context.Response.OutputStream
    }

Upvotes: 2

buley
buley

Reputation: 29248

The easiest way to export data from C# might not be the easiest way to consume data in JavaScript, but I'll give it a stab from the latter point of view.

Likely the best way to do this from the JavaScript perspective would be to export the contents of your query to a JSON representation, perhaps using JSONP to transfer it to the client. You can use a standard XMLHttpRequest to GET that data from your server, and from there parse it on the client side for use in JS.

The site JSON.org has a list of many JSON parsers/serializers available in C#.

Upvotes: 3

Related Questions