簡體   English   中英

從JavaScript向C#字典添加項目

[英]Adding items to C# dictionary from JavaScript

將ASP.NET/JavaScript代碼中的鍵/值對添加到C#詞典的可接受方式是什么(如果有)? TIA。

我如何處理此要求的方法是在javascript中的名稱值對中獲取所有數據,然后通過ajax將其發布到服務器...

例如loc是您的頁面,methodName是頁面后面的代碼中的WebMethod,可以填充為以下參數

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
});

在后面的代碼中,創建一個Web方法,例如

[System.Web.Services.WebMethod(EnableSession = true)]
public static string ItemsForDictionary(string data)
{
    Dictionary<String, String> newDict = ConvertDataToDictionary(data);
}

我使用通用方法將該代碼背后的數據參數轉換為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;
    }

無論如何..希望這給你這個主意...

您不能直接這樣做。 您必須使用回發或ajax調用將數據發送回服務器,然后將數據添加到服務器端處理程序中的Dictionary中。

如果您發布一些代碼來顯示您實際上在嘗試做什么,我們可能會更有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM