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.
Related
I want to call a method from a controller to calculate a basic arithmetic operation. However, I get only undefined error. My code is
$("#equals3").click(
function () {
let display = $("#calculatorDisplay");
let currentValue = display.val();
$.ajax({
url:'Calculator/EvaluateExpressionAJAX',
type: 'POST',
data: { expression: currentValue },
contentType: 'application/json; charset=utf-8',
success: function (response) {
if (response.success) {
alert(response);
} else {
alert(response.responseText);
}
},
error: function (response) {
alert("error!");
}
});
});
My controller contains
public static Dictionary<string, ArithmeticOperation> EvaulationDictionary = new Dictionary<string, ArithmeticOperation> {
{ "+", (a, b) => a + b},
{ "-", (a, b) => a - b},
{ "*", (a, b) => a * b},
{ "/", (a, b) => a / b},
{ "%", (a, b) => a % b} };
[HttpPost]
public double EvaluateExpressionAJAX(string expression)
{
expression = expression.Trim();
string[] splitExpression = Regex.Split(expression, #"\s+");
double a = Convert.ToDouble(splitExpression[0]);
double b = Convert.ToDouble(splitExpression[2]);
string op = splitExpression[1];
return EvaulationDictionary[op](a, b);
}
Thanks in advance
If you would put a breakpoint in the javascript you'll probably find that MVC/WebApi returns an error page with a message like:
Invalid JSON primitive: expression
The JSON that you post is not valid, it isn't even JSON.
If you would replace that with:
data: "{ \"expression\": \"" + currentValue +"\" }",
That would post valid json to the ActionMethod.
A better option would be to create a JavaScript Object and stringify that, like this:
// create a js object before the Ajax call
let dataObj = { "expression": currentValue };
// change the data you send to this
data: JSON.stringify(dataObj),
And secondly: Take a good look at the url, I can't be sure, but if the page you rendered this from is the same controller and the index method, this probably won't work as you would expect. Change the URL to:
url:'/Calculator/EvaluateExpressionAJAX',
to make it absolute.
And finally, there are lot of possible bugs in the Action method. You can't expect users to supply 3 parts where part 1 and 3 are doubles. So there is a lot of checking missing.
And last but not least, if this is MVC, it is probably best to return ActionResult or some subtype, in this case JsonResult would suit best, from an actionmethod.
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
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.
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
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.