RouteMapper
RouteMapper

Reputation: 2560

Convert Results of LINQ to SQL Query to XML/JSON

I wish to populate a JavaScript array with the results of a database query. From what I understand, a good approach is to populate a bunch of directories on my server with serialized XML or JSON files which my JS functions can then read into without having to access the database. Is this true? Should the database write these XML files upon user interaction, or should they be prepopulated?

Upvotes: 1

Views: 3346

Answers (2)

gdp
gdp

Reputation: 8242

From the details you have provided:

I Personally would create a Web Service endpoint returning your linq query serialized to JSON using JSON.NET or an equivalent. The endpoint can then be called using ajax within your client page.

You can check this example out on ASP.NET for how to create a asmx (legacy) web service. Also you can look at this example of using the [WebMethod] attribute .

A web method in your code behind files.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string GetMyQueryResultsAsJson()
{
    var results = GetQueryResults();
    var jss = new JavaScriptSerializer();
    string json = jss.Serialize(results);
    return json;
}

A ajax call on your client page:

function loadData() {
   var myArray = []; 
   $.getJSON("<%= ResolveUrl("~/MyPage.aspx/GetMyQueryResultsAsJson") %>", function (data) {
       $.each(data, function(obj) {
           myArray.push([obj.id, obj.someValue, obj.AnotherValue]);
       });
   });
}

Upvotes: 1

शेखर
शेखर

Reputation: 17614

I used jQuery ajax with generic http handler returing json
I created handler and put my business logic there.
It return me the result in form of json
I iterated the json using jquery.
And created my html form that.

Edit 1

Here are some useful links
http://www.codeproject.com/Articles/203621/Call-HTTPhandler-from-jQuery-Pass-data-and-retriev
http://www.sharepointnutsandbolts.com/2010/11/sp2010-ajax-part-4-returning-json-from.html

Edit 2

You can also take benefit of jtemplate
http://www.joe-stevens.com/2010/01/05/using-the-jtemplate-jquery-plugin-with-ajax-and-asp-net/
http://encosia.com/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/

Upvotes: 1

Related Questions