標籤:mvc autocomplete
Autocomplete外掛程式的功能類似於Google Suggest 功能,可以在使用者輸入查詢條件的時候,自動提示使用者若干詞條,方便使用者快速查詢。下面我們介紹下autocomplete外掛程式如何在MVC下面使用。
首先,需要下載autocomplete外掛程式,其是:http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
其次,需要在頁面上引入兩個檔案(jquery檔案除外),分別是jquery.autocomplete.js 和jquery.autocomplete.css,代碼如下:
<script src="@Url.Content("~/Content/autocomplete/jquery.autocomplete.js")" type="text/javascript"></script><link href="@Url.Content("~/Content/autocomplete/jquery.autocomplete.css")" rel="stylesheet"type="text/css" />
前端頁面只需要添加一個文字框,代碼如下:
<input type="text" name="HigherUserID" id="HigherUserID" />
需要編寫的js代碼如下所示:
<script type="text/javascript"> $(function () { $("#HigherUserID").autocomplete("/User/GetUserByUserName", { dataType: "json", minChars: 0, width: 200, showName: "TrueName", selfAction: SalesDeleteName, cacheLength: 0, autoFill: false, formatItem: function(row, i, max) { return i + "/" + max + ": \"" + row.TrueName + "\" [" + row.UserCode + "]"; }, formatResult: function(row) { return row.TrueName; } }).result(function(event, row) { }); }) </script>
後台代碼為根據條件檢索人員資訊,分頁顯示,返回給前端一個json資料:
public ActionResult GetUserByUserName(string q) { int _totalCount = 0; QueryUser query = new QueryUser(); query.truename = q; query.state = "0"; var userlist = UserService.GetUsersByPage(query, 10, 1, out _totalCount); IList<UserInfo> users = userlist.ToList<UserInfo>(); return Json(users, JsonRequestBehavior.AllowGet); }
MVC下autocomplete外掛程式的使用