Convert Results of LINQ to SQL Query to XML/JSON - asp.net

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?

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]);
});
});
}

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/

Related

asp.net return data in Page_Load

If a query string param exists in my page request I want to query the database on the server in the Page_Load and then return the result to the client. I can do the query string param check and query the DB but how do I return the data to the page and on the javascript side how do I access that data?
Ideally I would return JSON of an object structure and it would be returning an array of them.
Yes, returning JSON would be the best option. I'm not sure how you query your database (Do you use LINQ or ADO.NET DataTables, etc)
If you don't have custom object of type you want to send, I recommend you create one. Then you should get an array of them.
Example:
public class Person {
string Name { get; set; }
int Age { get; set; }
}
Person[] pArr = new Person[5];
Then you can use a third party library like this to create an string representaion of that array in JSON.
string json = JsonConvert.SerializeObject(product);
Then you write that json string to the Response object so its sent down to the client, by overriding the Render method of the page.
// Don't expect this code to work as it is, but take this as a guidance
Response.Clear();
Response.Write(json);
Response.Close();
on the client side use jQuery library send a request to page, and process the JSON response for you.
$.getJSON('url', function(data) {
//process data
});
Here is my suggestion if you don't want to use an AJAX request for this:
Use the objects as you would normally do in the page_load, and convert it to a JSON string as explained above.
Then use ClientScriptManager to create an JavaScript variable on the client side when it loaded.
ClientScript.RegisterClientScriptBlock(typeof(Page), "unique_key", "var myObjectList = " + json, true);
After this when the page loads you will have an variable named "myObjectList" with the list of objects without having to make a different AJAX call.
You can directly refer that variable in your javascript and do necessary processing.
Hope this helps.

Can Web API convert XML into Json?

I've got a legacy web service which I'd like to wrap with a new MVC Web API, question is can I get the ASP.NET Web API to convert my xml into json?
A thought that I had was to use XDocument to create a dynamic object and return that, but when I tried it with an ExpandoObject unfortunately it returned a json object with Key/Value pairs.
Using json.NET you can do it easily:
string result = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmldocument);
Download Newtonsoft.Json at http://james.newtonking.com/pages/json-net.aspx
You could. One way to do it would be to deserialize the XML into objects and then serialize them again into JSON.
A more efficient (though harder to code up approach) would be to write your own xml-to-json "transcriber" that reads in the XML and spits out JSON.
Just note that not all XML can be represented easily as JSON.
Turns out this can be done by converting an XDocument to a dynamic JsonObject like so roughly:
var doc = XDocument.Load(uri);
foreach (var node in doc.Root.Descendants()) {
var obj = (dynamic) new JsonObject();
foreach (var child in node.Descendants())
{
obj[child.Name.LocalName] = child.Value;
yield return obj;
}
}
In WebApiConfig file inside Register function add the below code at last (WebApiConfig file is at App_Start folder)
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
config.Formatters.Remove(config.Formatters.XmlFormatter);

jQuery-AJAX calling ASP.NET page method. How to return value back to jQuery?

If I use jQuery AJAX to call a specific ASP.NET page method how to have that method return a value back to the AJAX method that called it?
Update
My situation is I have an existing web application with many existing methods. I would like to be able to use jQuery to execute some of these methods and then update the UI with the results. My mandate is to stay away from ASP.NET AJAX and stick with jQuery. Management is concerned about continued development and support with ASP.NET AJAX from Microsoft. I agree with them.
You can use JQuery with page methods this way: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
The success callback contains a parameter with the returning data.
HTH.
There are two ways to skin this cat (that I am familiar with).
The ".Net Way" which involves a Web Method and a Script Manager (see here: http://geekswithblogs.net/frankw/archive/2008/03/13/asp.net-ajax-callbacks-to-web-methods-in-aspx-pages.aspx).
The "Old Skool Way" which involves simply writing a response out by determining what was called. Typically you'd use a framework like MVC so going to http://www.MyWebsite.com/Object/Method/Id can map back to Object.Method(id).
You can do this without a framework like MVC but it makes things a little more difficult and, if you go that route, you should really use an ASP.Net handler rather than an actual page (since you don't need the Aspx overhead). This is an Ashx file.
With pure ASP.NET (not talking WCF here) I'd go with a handler (ASHX) file, and use JSON as the interchange format. I won't get into the details of JSON (here is a decent start), but the idea is a lightweight handler on the server that generates json text and returns it to the client, which can then use the structure easily in javascript.
This is obviously a simplified example but the gist is the JSON can be data driven from the server and easily consumed by the javascript on the client.
server:
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/json";
context.Response.WriteFile("~/myData.json");
}
public bool IsReusable {
get {
return false;
}
}
}
client:
myData =
(function ()
{
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "handler.ashx",
'dataType': "json",
'success': function (data) {
// this code is called when the
// data is returned from the server
json = data;
}
});
return json;
}
)();
alert(myData.MyArray[0].MyProperty);

ASP.NET / JavaScript - Ajax call, how to?

Please be gentle, as I'm still new to web programming and -very- new to Ajax!
I've created a C# function which extracts data from an mssql database, formats it to a json string and returns that. Now I need to make a call from my javascript (jQuery) slider through an aspx page that is related to the C# code file.
I have actually never done anything like this before, from what I could tell by googling I need to use xmlHttpRequest, but how exactly do I make the function get hold of this string?
It would be awesome if someone had some example code that shows how this works.
The simplest way to do this is to convert your function into an ASHX file that writes the JSON to the HTTP response.
You can then call it using XmlHttpRequest, although you can call it much more easily using jQuery.
You can call it with jQuery like this:
$.get("/YourFile.ashx", function(obj) { ... }, "json");
It's relatively easy with jQuery if you mark the C# function as a [WebMethod] or make it part of a ASP.NET webservice. Both these techniques make it easy to have the response automatically converted into a JSON object by ASP.NET, which makes processing on the client easier (IMHO).
The example below is if the page has a WebMethod named GetData, but it's trivial to change the URL if you create a service.
$.ajax({ url: "somepage.aspx/GetData",
method: "POST", // post is safer, but could also be GET
data: {}, // any data (as a JSON object) you want to pass to the method
success: function() { alert('We did it!'); }
});
On the server:
[WebMethod]
public static object GetData() {
// query the data...
// return as an anonymous object, which ASP.NET converts to JSON
return new { result = ... };
}

How can we integrate jQuery autocomplete using asp.net, webservice and sql database?

I am trying to implement the code given for "jQuery Autocomplete and ASP.NET",
but unable to integrate it because you are using subsonic to query database.
So can you tell me how to query sqldatabase and bind the query result to the plugin from webservice in asp.net using C#?
This is a pretty easy task, the catch is that the jQuery autocomplete extender expects an array of values. Here is example of how I parse the standard XML results from a ASMX web serivce to use with the jQuery autocomplete extender.
Since ASP.NET likes to rewrite your ID's, you can pass in the ClientID to get the dynamic ID.
$("#<%= TextBox1.ClientID %>").autocomplete("/Demo/WebSvc.asmx/SuggestCustomers", {
parse: function(data) {
var parsed = [];
$(data).find("string").each(function() {
parsed[parsed.length] = {
data: [$(this).text()],
value: $(this).text(),
result: [$(this).text()]
};
});
return parsed;
},
dataType: "xml"
});
Here is what the associated web service would look like, remember to uncomment the [ScriptService] attribute on the web service:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebSvc: WebService
{
[WebMethod]
public string[] SuggestedCustomers(string q)
{
// Do Query
// Add items into string array
List<string> items = new List<string>();
while (dr.Read())
{
items.Add(dr[0].ToString());
}
// Return array
return items.ToArray();
}
}
I am not fluent in asp.net but fundamentally like most web coding questions this involves breaking your problem into smaller ones.
From an architectural perspective your components might include the following...
a service layer that potentially uses your db etc to answer or produce a result for your query.
a web component or service entry point that uses the completed service mentioned above to return the data in a format the browesrr can easily understand - eg JSON.
some javascript using jquery which invokes the end point define in the immediate point above.
write unit tests for all the above components - don't forget to test failure cases because as we all know software sometimes fails ...

Resources