how to reference a JSON object element by column - c#

I'm scraping some code together from samples on the web that takes a single row of data (returned row from SP) and uses JSON object serializer to send it back to the client aspx javascript page. To give you an idea of how the data is being built...
public static string GetLogEntry(DataTable table, string id)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in table.Select("UID =" + id))
// foreach (DataRow dr in table.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
var json = jss.Serialize(rows);
return json;
I understand I have an unnecessary loop here because this particular SP is only designed to return a single row. I'll be working on that in the next chapter. My real issue is I don't understand how to extract the data I need.
My client loop is returning the data but I'm having a hard time referencing specific column data individually.
success: function (json) { //ajax call success function
var obj = jQuery.parseJSON(json); // this line isn't really doing anything right now
eval("var datax = " + json);
for (var propertyName in $(datax)[0]) {
alert('data: ' + propertyName ); } //this returns only the column names
$(data).each(function (key, val) {
for (var propertyName in val) {
alert('data: ' + val[propertyName]); }
So what I'm wanting to do is access an element by the column name like I've seen in other examples....
alert(json.columnName) //returns undefine.
Thanks in advance for your time.

Depending on how your ajax call is made, the variable json in your success handler is already a javascript object literal.
function successHandler(resp){
var data = resp;
$.each(data, function (index, row){
var key;
foreach (key in row){
if (row.hasOwnProperty(key)){
console.log(key, row[key]);
}
}
});
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "some url",
data: "{}",
dataType: "json"
}).done(successHandler);
It would help a lot if you could post the data as returned by the server. That would give us an idea of the structure of json.
As such, there shouldn't be any need to use eval or to parse the server response.
Btw, there is no such thing as a JSON object. JSON is simply a format to serialize and pass around javascript object literals. The following,
var data = new List<Dictionary<string, object>>
{
new Dictionary<string, object>
{
{ "Col1", 1.0}, { "Col2", 2.0}
},
new Dictionary<string, object>
{
{ "Col1", 1.1}, { "Col2", 2.2}
},
};
will be converted to the following string as per the JSON format:
"[{\"Col1\":1,\"Col2\":2},{\"Col1\":1.1,\"Col2\":2.2}]"
jQuery ajax will automatically parse this string and pass the resultant array to the success handler. For this to happen, jquery needs to be told to expect json data and the server needs to send back a string with the mimetype application/json; charset=utf-8

Related

Bind json variable data to the dropdownlist from jquery

In my asp.net web page, I have prepared the JSon string with the help of JavaScriptSerializer class.
And i have spit the Json string in to the HTML markup with the help of RegisterStartupScript method and it looks like this,
C#.net code to prepare the json string,
System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, string>> glAccts = new List<Dictionary<string, string>>();
Dictionary<string, string> row;
foreach (DataRow dr in _dtProfitCenterRawData.Rows)
{
row = new Dictionary<string, string>();
row.Add(dr[0].ToString(), dr[1].ToString());
glAccts.Add(row);
}
string jsonObj = jsSerializer.Serialize(glAccts);
string script = "var glList = " + jsonObj + ";";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(Page.GetType(), "JSONObj", script, true);
The glList variable on the client html looks like this,
var glList = [
{ "1110005": "1110005 - X1" },
{ "1110008": "1110008 - X2" },
{ "1110011": "1110011 - X3" },
{ "1110020": "1110020 - X4" }
];
I want to bind this json string to dropdownlist control. Please suggest how to perform that? I tried to perform the following action to view the data inside the object, but it does not give me the real values. It gives [object] in the alert methods.
Please suggest the fix to the problem..
$.each(glList, function (val, text) {
//$('#mySelect').append(new Option(text, val));
alert(text); alert(val);
});
Try this here. If you itereate through glList you get the objects but not their properties.
function jsonTest() {
$.each(glList, function(index, obj) {
($.each(obj, function (key, value) {
$('#mySelect').append(new Option(key, value));
}));
});
}
Use JSON.Net instead JavaScriptSerializer to serialize a Dictionnary.
Or you can try to cast to object before serialize
jsSerializer.Serialize((object)glAccts)
try
var glList = [
{ 1110005: "1110005 - X1" },
{ 1110008: "1110008 - X2" },
{ 1110011: "1110011 - X3" },
{ 1110020: "1110020 - X4" }
];

Sql Table values in JSON c#

Hi i have a table with following values
Country Count
China 2
India 3
Pakistan 3
i want these in JSON as "China" : 2,"India" : 3,"Pakistan" : 3
I don't want the header Count and Country. I Have tried using ajax and HTTP Handler but no avail
$(document).ready(function () {
$.ajax({
url: 'CountryRegistrations.ashx',
type: 'POST',
dataType: 'json',
success: function (data) {
var test = data.Country + data.Count;
alert(test);
},
error: function (data) {
alert("Error");
}
});
});
public void ProcessRequest(HttpContext context)
{
FilterCountry emp = getCounts();
// serialize and send..
JavaScriptSerializer serializer = new JavaScriptSerializer();
StringBuilder sbJsonResults = new StringBuilder();
serializer.Serialize(emp, sbJsonResults);
context.Response.Clear();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(sbJsonResults.ToString());
}
private FilterCountry getCounts()
{
FilterCountry fc = new FilterCountry();
fc.Country = "PK";
fc.Count = 600;
return fc;
}
I gives me as PK600 but it should give "PK":600 and how to get these values from database right now im trying to get from hard coded values.
var test = data.Country + data.Count;
Try to change to:
var test = data.Country + ':' + data.Count;
If you are using JavaScriptSerializer then it will will serialize the object in to JSon format like "Key":"Value" that is also based on the object you are passing to Serialize method.
Your class "FilterCountry" has two property "Country" and "Count" and assigning values on it.
So it will be serialize like as follows { "Country" : "PK", "Count":600 }
Please go through JSon and serialize examples

How to a Deserialize Json object made by JavaScriptSerializer from a List in jQuery/Javascript

Okay I am serializing a bunch of years from a database call into a json object.
This object is the response from the webservice to the first ajax call. My javascript error console throws an error on the line where it is suppose to deserialize it. I am trying to figure out what is wrong.
Update:
This code works, thanks to Jussi Kosunen
$.ajax(
{
type: "POST",
url: "default.aspx/HelloWorld",
dataType: "json",
data: "{name:'" + name + "'}",
contentType: "application/json; charset=utf-8",
success: function (msg) {
//parse the object into something useable.
var stringarray = JSON.parse(msg.d);
//empty the results for next time around.
$('#year').empty();
for (index in stringarray) {
$('#year').append('<option>' + stringarray[index] + "</option>");
alert(stringarray[index]);
}
This is the C# that serialized the list into an json object;
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static string HelloWorld(string name)
{
string splitme = "USE VCDB SELECT DISTINCT YearID FROM BaseVehicle";
DataTable dt = getDataTable(splitme);
List<string> ids = new List<string>();
foreach (DataRow row in dt.Rows)
{
ids.Add(row.ItemArray[0].ToString());
}
JavaScriptSerializer js = new JavaScriptSerializer();
string x =js.Serialize(ids);
return x;
}
Now when I go into debug. this is the string the C# is returning.
[\"1896\",\"1897\",\"1898\",\"1899\",\"1900\",\"1901\",\"1902\",\"1903\",\"1904\",\"1905\",\"1906\",\"1907\",\"1908\",\"1909\",\"1910\",\"1911\",\"1912\",\"1913\",\"1914\",\"1915\",\"1916\",\"1917\",\"1918\",\"1919\",\"1920\",\"1921\",\"1922\",\"1923\",\"1924\",\"1925\",\"1926\",\"1927\",\"1928\",\"1929\",\"1930\",\"1931\",\"1932\",\"1933\",\"1934\",\"1935\",\"1936\",\"1937\",\"1938\",\"1939\",\"1940\",\"1941\",\"1942\",\"1943\",\"1944\",\"1945\",\"1946\",\"1947\",\"1948\",\"1949\",\"1950\",\"1951\",\"1952\",\"1953\",\"1954\",\"1955\",\"1956\",\"1957\",\"1958\",\"1959\",\"1960\",\"1961\",\"1962\",\"1963\",\"1964\",\"1965\",\"1966\",\"1967\",\"1968\",\"1969\",\"1970\",\"1971\",\"1972\",\"1973\",\"1974\",\"1975\",\"1976\",\"1977\",\"1978\",\"1979\",\"1980\",\"1981\",\"1982\",\"1983\",\"1984\",\"1985\",\"1986\",\"1987\",\"1988\",\"1989\",\"1990\",\"1991\",\"1992\",\"1993\",\"1994\",\"1995\",\"1996\",\"1997\",\"1998\",\"1999\",\"2000\",\"2001\",\"2002\",\"2003\",\"2004\",\"2005\",\"2006\",\"2007\",\"2008\",\"2009\",\"2010\",\"2011\",\"2012\",\"2013\"]
As you're passing dataType: "json" into your $.ajax call, it's parsing your JSON automatically.

Send data from ajax to c# server

I've created a dictionary on cliend side and want to send it on sever side. In my script, dictionary is created correctly, but I'm not sure abount my ajax code.
$("#btnSubmit").click(function () {
var sendList = new Array();
var elems = $(".elemValue");
$.each(elems, function (key, value) {
if (value.attributes.elemName.nodeValue != "PhotoImg") {
sendList[value.attributes.elemName.nodeValue] = value.attributes.value.nodeValue;
}
});
var data = JSON.stringify({dict : sendList});
$.ajax({
type: "GET",
url: "dataloader.aspx/GetData",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result){
alert(result.d);
}
});
});
On server side I wrote
[System.Web.Services.WebMethod]
public static string GetData(Dictionary<string,string> dict)
{
Dictionary<string, string> serverDict = new Dictionary<string, string>();
serverDict = dict;
string result = "";
foreach (var value in dict)
{
result += "The key is:" + value.Key + "The value is:" + value.Value;
}
return result;
}
Where are my mistakes, and how can I fix them? Help, please=)
I don't think it's possible to create a Dictionary from JSON. At least not without a lot of work. I would try changing it from a Dictionary to a List<KeyValuePair<string,string>> and see if it deserializes for you.
Reference for KeyValuePair
Once you've done that if you still need the Dictionary you can convert it fairly easily.
var Dictionary = new Dictionary<string,string>();
foreach(var KVP in List) Dictionary.Add(KVP.Key, KVP.Value);
Couple of things here:
You need to allow GET verb explicitly:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet=true)]
You are returning plain text from the server, which means that this line:
dataType: "json"
won't let jQuery parse the response correctly. You should either remove this line, or build response in JSON format.

Adding items to C# dictionary from JavaScript

What, if any, is the accepted way of adding a key-value pair from ASP.NET/JavaScript code to a C# dictionary? TIA.
How I've handled this requirement is to get all the data in a name value pair in javascript, then post this to the server via ajax ...
e.g.
loc is your page,
methodName being the WebMethod in code behind page,
arguments you can populate as
var arguments = '"data":"name1=value1&name2=value2"';
$.ajax({
type: "POST",
url: loc + "/" + methodName,
data: "{" + arguments + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
fail: onFail
});
On your code behind, create a web method
e.g
[System.Web.Services.WebMethod(EnableSession = true)]
public static string ItemsForDictionary(string data)
{
Dictionary<String, String> newDict = ConvertDataToDictionary(data);
}
I use a generic method to convert this data parameter in codebehind to a Dictionary.
private static System.Collections.Generic.Dictionary<String, String> ConvertDataToDictionary(string data)
{
char amp = '&';
string[] nameValuePairs = data.Split(amp);
System.Collections.Generic.Dictionary<String, String> dict = new System.Collections.Generic.Dictionary<string, string>();
char eq = '=';
for (int x = 0; x < nameValuePairs.Length; x++)
{
string[] tmp = nameValuePairs[x].Split(eq);
dict.Add(tmp[0], HttpUtility.UrlDecode(tmp[1]));
}
return dict;
}
Anyways .. hope this gives you the idea ...
You can't do it directly. You'd have to send the data back to the server using a post-back or ajax call, and then add the data to the Dictionary in the server-side handler.
We could probably be more helpful if you post some of your code to show what you're actually trying to do.

Categories

Resources