2011-04-16 27 views
0

我有一個返回類似於下面的web服務功能:將密鑰和價值觀在字典<int, string>爲String []數組

  • 路易斯安那州新奧爾良市
  • 紐約,紐約
  • 紐瓦克新澤西州

這個數據來自於以下幾個功能:

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string[] GetCitiesWithState(string isoalpha2, string prefixText) 
{ 
    var dict = AtomicCore.CityObject.GetCitiesInCountryWithStateAutocomplete(isoalpha2, prefixText); 
    string[] cities = dict.Values.ToArray(); 
    return cities; 
} 

它奇妙的作品,但我真的需要是一個列表這樣

  • 12,新奧爾良,路易斯安那州
  • 22,紐約,紐約
  • 48,紐瓦克,新澤西州

與#是城市Id(這是包含dict,這是類型:Dictionary<int, string>)。

我這樣做的原因是因爲我有一些讀取ASMX服務和此方法的Jquery,我需要能夠看到所選城市的城市ID。這是我對jQuery的透明度(其中工程目前):

$('#<%=txtCity.ClientID%>').autocomplete({ 
      source: function (request, response) { 
       var parameters = { 
        isoalpha2: '<%=Session["BusinessCountry"].ToString()%>', 
        prefixText: request.term 
       }; 
       $.ajax({ 
        url: '<%=ResolveUrl("~/AtomicService/Assets.asmx/GetCitiesWithState")%>', 
        type: 'POST', 
        dataType: 'json', 
        contentType: 'application/json; charset=utf-8', 
        data: JSON.stringify(parameters), 
        success: function (data) { 
         response($.each(data.d, function (index, value) { 
          return { 
           label: value, 
           value: index 
          } 
         })); 
        } 

       }); 
      }, 
      select: function (event, ui) { 
       $('#<%=txtState.ClientID%>').val(ui.value); 
      }, 
      minLength: 2, 
      delay: 500 
     }); 

最後,什麼,我其實是想實現的是當用戶選擇在從懸掛自動完成城市:$('#<%=txtCity.ClientID%>'),我想的Jquery將價值分割(例如,路易斯安那州的新奧爾良分爲兩個(新奧爾良)和(路易斯安那州)),那麼我會認爲'新奧爾良'是價值$('#<%=txtCity.ClientID%>')和'路易斯安那'是價值$('#<%=txtState.ClientID%>') ..任何獲得這種瘋狂的幫助總是值得讚賞的:)

回答

2

如果我明白你的理解,你只需要從WebMethod中返回數據有點不同:

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string[] GetCitiesWithState(string isoalpha2, string prefixText) 
{ 
    var dict = AtomicCore.CityObject.GetCitiesInCountryWithStateAutocomplete(isoalpha2, prefixText); 
    string[] response = dict.Select(x => String.Format("{0}, {1}", x.Key, x.Value)).ToArray(); 
    return response; 
} 

而現在,在JavaScript端,您需要將字符串分割成indexlabel手動(因爲什麼index現在只是一個行號,我相信)。類似的東西(只是草稿):

response($.each(data.d, function (index, value) { 
    return { 
     label: value.slice(value.indexOf(',')), 
     value: parseInt(value.split(',')[0]) 
    } 
})); 
+0

超級答案答:非常感謝。 LINQ特別有效! – dooburt 2011-04-16 14:17:59

相關問題