代码改变世界

使用 jQuery.TypeAhead 让文本框自动完成 (三)(服务器返回 JSON 复杂对象数组)

  音乐让我说  阅读(298)  评论(0编辑  收藏  举报

项目地址:https://github.com/twitter/typeahead.js

直接贴代码了:

复制代码
@section headSection
{
    <script type="text/javascript">
    $(document).ready(function () {
        var bestPictures = new Bloodhound({
          datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
          queryTokenizer: Bloodhound.tokenizers.whitespace,
          identify: function(obj) { return obj.id; } /* 这个函数是告诉引擎对象的 ID */,
          remote: {
            url: '@Url.Action("Trade_Code_List_Search_By_Trad_Cod")?searchTradCode=%QUERY',
            wildcard: '%QUERY'
          }
        });

        $('#trad_cod_textbox').typeahead(null,{
            name: 'best-pictures',
            source: bestPictures,
            display: 'value',
            limit:10
        }).bind('typeahead:select', function(ev, suggestion) {
            alert("you select: " + "(id=" + suggestion.id + ", value="+ suggestion.value +")"); //绑定自定义事件
        });
    });
    </script>
}
@Html.Partial("UCjQueryTypeAheadJsScript")

<!-- 这里就是文本框 -->
<input id="trad_cod_textbox" class="text-input" type="text" value="">
复制代码

 

UCjQueryTypeAheadJsScript.cshtml

<!-- both bloodhound.js and typeahead.jquery.js have a dependency on jQuery 1.9+. -->
<script src="~/resources/plugins/jQuery-type-ahead.js/typeahead.bundle.min.js"></script>
<link href="~/resources/plugins/jQuery-type-ahead.js/examples.css" rel="stylesheet" />

Controller.cs

 

复制代码
        public ActionResult Trade_Code_List_Search_By_Trad_Cod(string searchTradCode)
        {
            List<Trd_Mas_Simple_Info> simpleTradMasList = new Trd_MasService().GetSimpleListByTradCode(searchTradCode);
            return Json(simpleTradMasList.Select(c => new
            {
                value = c.trd_cod + " - " + c.trd_des,
                id = c.trd_cod
            }), JsonRequestBehavior.AllowGet);
        }
复制代码

examples.css

 

.tt-query { -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); }
.tt-hint { color: #999 }
.tt-menu { width: 422px; margin: 12px 0; padding: 8px 0; background-color: #fff; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, 0.2); -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2); -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2); box-shadow: 0 5px 10px rgba(0,0,0,.2); }
.tt-suggestion { padding: 3px 20px; font-size: 18px; line-height: 24px; }
.tt-suggestion:hover { cursor: pointer; color: #fff; background-color: #0097cf; }
.tt-suggestion.tt-cursor { color: #fff; background-color: #0097cf; }
.tt-suggestion p { margin: 0; }
.gist { font-size: 14px; }

 

运行后

 

 

谢谢浏览!

点击右上角即可分享
微信分享提示