简体   繁体   中英

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 ...

eg 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 eg

[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM