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
SHeinema
  • 634
  • 5
  • 14
  • 34

3 Answers3

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

buley
  • 28,032
  • 17
  • 85
  • 106
  • Check out this question, likely of interest: http://stackoverflow.com/questions/1212344/parse-json-in-c-sharp – buley Jan 20 '12 at 23:21
  • Ok, getting closer but now I am getting an error. Posted above ^^ Any thoughts on that? – SHeinema Jan 21 '12 at 00:34
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

bbqchickenrobot
  • 3,592
  • 3
  • 45
  • 67
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
    }
doogle
  • 3,376
  • 18
  • 23
  • You can use built in one if your needs are simple - http://msdn.microsoft.com/en-us/library/bb412179.aspx – Alexei Levenkov Jan 20 '12 at 23:27
  • 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...) – SHeinema Jan 20 '12 at 23:48
  • 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. – doogle Jan 20 '12 at 23:55
  • Ok, getting closer but now I am getting an error. Posted above ^^ Any thoughts on that? – SHeinema Jan 21 '12 at 00:31
  • 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 – doogle Jan 21 '12 at 00:56
  • This indeed solved the first error but now I'm getting the dreaded: "A circular reference was detected while serializing an object of type 'System.Data.Metadata.Edm.AssociationType'." error! – SHeinema Jan 21 '12 at 01:49
  • This could be because the serialization is triggering a lazy load on any navigation properties in your entities. Try serializing the entities outside of the using block. This will prevent lazy loading of any associations. Another thing you could try to do is create a DTO object and serialize the DTO object instead of the entity. Database/Model first entities tend to carry a huge amount of extra code with them that makes serializing them a pain. – doogle Jan 21 '12 at 02:11
  • Alright! Finally got it to work! I ended up using json as you suggested, I just wasnt able to pass a serialized list of the entire objects, but once I reduced that to just the pieces I needed it worked! ( : Thanks. – SHeinema Jan 21 '12 at 09:01