What, if any, is the accepted way of adding a key-value pair from ASP.NET/JavaScript code to a C# dictionary? TIA.
-
What is the persistence of the C# dictionary? As both bits of code are executed at separate times, the persistence of the dictionary will need to be greater than that of simply the page life-cycle.Richard– Richard2012-06-27 23:32:08 +00:00Commented Jun 27, 2012 at 23:32
-
I have tried using post-backs but I seem to lack the knowledge for implementing several independent post-back loops (since I am already having a post-back event that processes some other data). I know C# reasonably well but I'm new to using it together with ASP/JS.Arets Paeglis– Arets Paeglis2012-06-27 23:46:28 +00:00Commented Jun 27, 2012 at 23:46
2 Answers
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 ...
1 Comment
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.