前面使用Jquery autocomplete对输入框进行自动填充代码编写,如果远程url获取的数据为单纯的string返回的json数据,那么就可以正常显示,如果是返回的复杂的json数据就无法正常相应,非常的郁闷,在此记录一下解决该问题的方法,希望对遇到此类问题的童鞋们能够有所帮助。
1、引入jquery的相关js和css代码
@Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
@Styles.Render("~/Content/jquery-ui.css")
@Scripts.Render("~/Scripts/jquery-ui.js")
2、基本的调用autocomplete的代码
客户端js代码
<script>
$("#Grade").autocomplete({
source: "/Products/GradeAutoComplete",
minLength: 1,
dataType: "json",
});
</script>
服务器代码
public ActionResult GradeAutoComplete(string term)
{
List<string> tmp = db.Products.Select(x => x.Grade).Distinct().Where(x => x.Contains(term)).ToList<string>();
return Json(tmp, JsonRequestBehavior.AllowGet);
}
["abcdefgh","Brazos","Laredo","San Jacinto","Scavino"]
3、返回复杂JSON数据格式时的其他调用模式
客户端代码
<script>
$("#SKU1").autocomplete({
source: function (request, response) {
var url = '/products/SkuAutoComplete?term=' + request.term;
$.ajax({
'url': url,
dataType: 'json',
success: function (dataObj) {
response(dataObj);
}
});
},
select: function (event, ui) {
$(this).value = ui.item.label;
$("#SKU").val(ui.item.value);
if (ui.item.ItemType == "Product")
{
$("#DVOthers").hide();
$("#DVProduct").show();
}
else
{
$("#DVOthers").show();
$("#DVProduct").hide();
}
event.preventDefault();
}
});
</script>
服务器代码
public ActionResult SkuAutoComplete(string term)
{
List<SkuSingle> tmp = new List<SkuSingle>();
//List<string> tmp = new List<string>();
foreach(var it in db.Skus.Where(x => x.name.Contains(term)))
{
Product_Item_Type_Lookup pitl = db.Product_Item_Type_Lookup.Find(it.ItemType);
tmp.Add(new SkuSingle { value = it.ID, label = it.name, barcode = it.barcode, ItemType = pitl.type });
//tmp.Add(it.name);
}
return Json(tmp, JsonRequestBehavior.AllowGet);
}
返回的JSON数据
[{"value":5,"label":"RGPA316Y","barcode":"811617024055","ItemType":"Product"},{"value":10,"label":"RRPA316","barcode":"812788019316","ItemType":"Product"}]
此时可以具备自动填充的内容,这里面最关键的是返回的JSON数据必须包含label和value的项,否则不能正常显示出自动填充的下拉框,而此处我也是浪费了一段时间,当然是因为我没有去看自动填充的注意事项的原因,也没有看到具体介绍。
4、注意事项
注意返回复杂JSON数据对象的时候,一定要具备label属性,否则不能够正常显示出自动填充的下啦框