在ASP.NET中使用jQuery UI Autocomplete

时间:2011-06-28 05:33:53

标签: c# jquery asp.net jquery-ui jquery-ui-autocomplete

我在ASP.NET中使用jQuery UI Autocomplete,如下所示: 首先,我将好的名称序列化为字符串数组,然后将Array传递给jQuery UI AutoComplete的源代码

   //PageLoad
    tadok.Entities.TList<tadok.Entities.Good> GoodEntites = tadok.Data.DataRepository.GoodProvider.GetAll();
    List<string> GoodNames = new List<string>();
    foreach (object item_loopVariable in GoodEntites) {
        item = item_loopVariable;
        GoodNames.Add(string.Format(item.GodTitle));

    }
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Values = serializer.Serialize(GoodNames);

MarkUp代码:

  var availableTags = <%= Values %>
       $("#txtGoodAutoComplete").autocomplete({
         source: availableTags

          });

我正在序列化的对象具有名称为ID的属性。如何在自动完成的选择项目事件中序列化ID和存储ID,例如隐藏字段?
更新 我的主要挑战是如何序列化ID?

1 个答案:

答案 0 :(得分:2)

使用select事件,

如果您的对象看起来像{'label':'A', 'value':'A', 'ID':'7897975'}

$( ".selector" ).autocomplete({
select: function(event, ui) { 
     $('#hiddenField').val(ui.item.ID);//Item is your selected object.
}
});

<强>更新

我从未参与过C#。但是应该有任何内置的JSON解析器。

在java中我创建像这样的JSON格式,

JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;

for(Country country : countries){
                jsonObject = new JSONObject();
                jsonObject.put("label", country.getName());
                jsonObject.put("value", country.getCode());
                jsonObject.put("id", country.getId().toString());
                jsonArray.add(jsonObject);
            }
String json = jsonArray.toJSONString();//The json string will look like, [{'label':'A', 'value':'A', 'id':'7897925'},{'label':'B', 'value':'B', 'id':'7497975'},{'label':'C', 'value':'C', 'id':'7843975'},{'label':'D', 'value':'D', 'id':'7857975'}]

//Your autocomplete source should return something like the above json string



使用Javascript Serializer: 首先添加一个类:

public class GoodAutoComplete
{
    public string label;
    public string value;
    public string ID;
}


然后像这样序列化对象:

tadok.Entities.TList<tadok.Entities.Good> GoodEntites = tadok.Data.DataRepository.GoodProvider.GetAll();
List<GoodAutoComplete> GoodItems = new List<GoodAutoComplete>();
foreach (object item_loopVariable in GoodEntites) {
    item = item_loopVariable;
    GoodItems.Add(new GoodAutoComplete {
        ID = item.GodId,
        label = string.Format(item.GodTitle + "{(0)}", item.GodDescrp).Replace("()", ""),
        value = string.Format(item.GodTitle + "{(0)}", item.GodDescrp).Replace("()", "")
    });
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
Values = serializer.Serialize(GoodItems);