1

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

3 Answers 3

3

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#.

Sign up to request clarification or add additional context in comments.

2 Comments

Check out this question, likely of interest: stackoverflow.com/questions/1212344/parse-json-in-c-sharp
Ok, getting closer but now I am getting an error. Posted above ^^ Any thoughts on that?
3

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

Comments

2

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
    }

8 Comments

You can use built in one if your needs are simple - msdn.microsoft.com/en-us/library/bb412179.aspx
ok I think I have the json serialization down but what is the code for passing it back to the client? (sorry new to asp.net...)
You'd make a simple ajax call, most JS frameworks make this task incredibly easy, jQuery for example has the $.ajax method. As far as what the client should call, I'd create an asp.net generic HttpHandler which could then get the data from the database and send it back tot he client via JSON in the response stream.
Ok, getting closer but now I am getting an error. Posted above ^^ Any thoughts on that?
By the looks of it though, it seems like the amount of results you are getting from the database is less than 10. Instead of GetRange, try Take(10) instead
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.