問題描述
從 JavaScript 將項目添加到 C# 字典 (Adding items to C# dictionary from JavaScript)
如果有的話,將 ASP.NET/JavaScript 代碼中的鍵值對添加到 C# 字典的公認方法是什麼?TIA。
參考解法
方法 1:
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 ...
方法 2:
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.
(by Arets Paeglis、Jo‑Pierre、Andrew Cooper)