2
我正在c#應用程序中,我已實現下面的函數來顯示自動完成功能,它工作正常。 我想要做的唯一事情是,當搜索時它顯示項目,那些顯示的項目應該顯示爲字段1 +字段2,但是當用戶選擇一個項目時,字段1應該填滿該文本框,所以基本上顯示項目和填寫項目應該是不同的。 這是我的工作代碼。jquery自動完成 - 如何顯示字段1 +字段2,並在選定時,只需填寫字段1在文本框中
<input type="text" id="txtInfo" class="form-control" >
<script type="text/javascript">
$(document).ready(function() {$('#txtInfo').autocomplete({
serviceUrl: 'Controller/MyActionMethod' ,
disabled: false,
minChars: 0,
dataType: 'json',
type: 'GET',
async: false,
deferRequestBy: 800,
transformResult: function (response) {
if (response != null) {
return {
suggestions: $.map(response, function (dataItem) {
return {
value: dataItem, data: dataItem
};
})
};
}
}
});
});
public JsonResult MyActionMethod(string query)
{
List<SelectListItem> MyIems = Session["myVal"] as List<SelectListItem>;
//MyIems has Text and Value, Text is the one I want to display and Value is the one which I want to get fill up
// in the txtInfo when user selects it.
// For example, if user searches and txtInfo displays text "Full Name", when he selects that, txtInfo should have
// filled up with "Value" of that item.
List<string> result = new List<string>();
List<string> displayResult = new List<string>();
foreach (var r in MyIems)
{
if (r.Text.ToLower().Contains(query.ToLower()) || r.Value.ToLower().Contains(query.ToLower()))
{
if (!result.Contains(r.Value)) result.Add(r.Value);
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}
任何幫助,將不勝感激, 在此先感謝
我嘗試過,但無法通過jquery成功綁定文本和值。我在jquery函數中做了什麼更改以顯示splitedresp [0],當用戶選擇它時,請在文本框中填寫splitedresp [1]。我的意思是在我返回這個字符串時應該做什麼改變。返回{ 建議:$ .MAP(響應,函數(的DataItem){ 調試器; 返回{ 值:DataItem的,數據:DataItem的 }; }) }; – Madhu2010
謝謝,我嘗試了上面的代碼,但是在我的結尾處缺少一些東西,它沒有加載任何東西,基本上它只是繼續處理。我用「|」返回字符串從actionmethod。這工作,但不知何故UI只是繼續旋轉。我嘗試了上面的代碼。 $( 「#txtInfo」)自動完成({ 的serviceUrl: '控制器/ myMethod的', 禁用:假, minChars:0, 數據類型: 'JSON', 類型: 'GET', 異步:假, deferRequestBy:800, – Madhu2010
對不起,無法解決此問題。任何其他想法? – Madhu2010