2013-07-30 44 views
0

我在cliend一侧创建了一本字典,并希望将它发送到服务器端。在我的脚本中,字典是正确创建的,但我不确定放弃我的ajax代码。将数据从ajax发送到c#服务器

$("#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); 
      } 
     }); 
     }); 

在服务器端,我写

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

哪里是我的错误,我怎样才能解决这些问题?帮助,请=)

+0

您是否收到任何错误? – Andrei

+0

不,任何错误。只是脚本根本不工作。即使是VS调试器也不会被调用。 –

+0

所以脚本没有发出AJAX请求? –

回答

0

夫妇的东西在这里:

  1. 您需要允许GET动词明确:

    [System.Web.Services.WebMethod] 
    [System.Web.Script.Services.ScriptMethod(UseHttpGet=true)] 
    
  2. 您是从服务器,这意味着该返回纯文本行:

    dataType: "json" 
    

    不会让jQuery正确解析响应。您应该删除此行,或者以JSON格式构建响应。

1

我不认为有可能从JSON创建一个字典。至少不是没有很多工作。我会尝试将它从Dictionary更改为List<KeyValuePair<string,string>>并查看它是否为您反序列化。

参考为KeyValuePair

一旦你这样做,如果你仍然需要解释,你可以很容易转换。

var Dictionary = new Dictionary<string,string>(); 
foreach(var KVP in List) Dictionary.Add(KVP.Key, KVP.Value); 
+0

问题出在ajax脚本中,因为它失败了。感谢这个答案,但首先我需要使这个代码工作。=) –

相关问题