将jsondata转换为NameValueCollection

时间:2013-05-28 07:26:51

标签: asp.net jquery webforms

我试图将JSON从jQuery传递到.ASHX文件。 我希望通过HttpContext和猫将.ASHX文件中的JSON数据检索到NameValueCollection。 怎么做?

$.ajax({
    url: "GetLetterInformationHandler.ashx",
    data: "{'Name':'david', 'Family':'logan'}",
    contentType: "application/json; charset=utf-8",
    type: "Get",
    datatype: "json",
    onSuccess: function (data) {

    }
}); 

现在我可以使用querystring和And转换如下:

  public void ProcessRequest(HttpContext context)
    {
        HttpResponse response = context.Response;
        string cururl = context.Request.Url.ToString();
        int iqs = context.Request.Url.ToString().IndexOf('?');
        string querystring = (iqs < cururl.Length - 1) ? cururl.Substring(iqs + 1) : String.Empty;
        NameValueCollection parameters = HttpUtility.ParseQueryString(querystring);
        context.Response.ContentType = "text/plain";
    }

我想使用json insted of querystring

2 个答案:

答案 0 :(得分:0)

试试这个:

$.map(data.d, function (item) {
    return {
       name: item.Name,
       family: item.Family
    };
})

或者如果你想要每个功能:

var resultData = data.d;
$.each(resultData, function() {
    alert(this)
})

答案 1 :(得分:0)

我做了一些改变希望这会对你有所帮助:)。

Ajax功能

$.ajax({
  type: "POST",
  url: "GetLetterInformationHandler.ashx",
  data: "{'Name':'david', 'Family':'logan'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data) {
               if( data != null){
                  if (data.msg == "SUCCESS"); {
                      alert( data.msg)
                  }
               }
           },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
               alert(textStatus);
         }
  });

.ASHX文件

public void ProcessRequest(HttpContext context) 
{     
   string outputToReturn = String.Empty;   // Set it to Empty Instead of  ""        
   context.Response.ContentType = "text/json";     

   var getName = String.Empty ;     
   var getFamily = String.Empty ;      // Make sure if the Particular Object is Empty or not
   if (!string.IsNullOrEmpty(context.Request["Name"]))         
     {           
        getName = context.Request["Name"];         
     }

   if (!string.IsNullOrEmpty(context.Request["Subject"]))        
     {             
        getFamily = context.Request["Subject"];         
     }

    NameValueCollection nvc = new NameValueCollection();
    nvc.Add(getName, getFamily);
    var dict = new Dictionary<string, string>();
    foreach (string key in nvc.Keys)
    {
        dict.Add(key, nvc[key]);
    }
    string json = new JavaScriptSerializer().Serialize(dict);
    Console.WriteLine(json);
}