【问题标题】:Twitter TypeAhead with Asp .NetTwitter TypeAhead 与 Asp .Net
【发布时间】:2013-10-29 12:53:17
【问题描述】:

大家好,谁能给我一个很好的例子,说明如何在带有数据库的 asp .net 中使用 Twitter Typeahead (http://twitter.github.io/typeahead.js/)。

谢谢

【问题讨论】:

    标签: asp.net typeahead.js


    【解决方案1】:

    在 ASP.NET MVC 中,您可以创建一个返回 JSON 的控制器操作,如下所示:

    查看

    @Html.TextBox("playerName")
    
    <script type="text/javascript">
    
        $(function () {
    
            $('#playerName').typeahead({
                name: 'players',
                valueKey: 'playerName'  
                prefetch: '@Url.Action("AvaliablePlayers", "Player")',
                limit: 10
            });
    
        });
    
    </script>
    

    控制器和动作

    public class PlayerController : Controller
    {    
        public JsonResult AvaliablePlayers(int groupId)
        {
            var group = _groupRepository.GetById(groupId);
    
    
            return Json(group.Players.Select(p => new { playerId = p.PlayerID, playerName = p.Name), JsonRequestBehavior.AllowGet);
        }
    }
    

    在 ASP.NET WebForms 中,您可以使用自定义 HTTP 处理程序以 JSON 格式返回数据,如下所示:

    默认.aspx

    <asp:TextBox id="country" CssClass="countryTypeAhead" runat="server"></asp:TextBox>
    
    <script type="text/javascript">
    
        $(function () {
    
            $('.countryTypeAhead').typeahead({
                name: 'countries', 
                prefetch: '<%= Page.ResolveClientUrl("~/Countries.ashx") %>',
                limit: 10
            });
    
        });
    
    </script>
    

    在您的项目中添加新的 Generic Handler (.ashx) 命名国家。这是处理程序的代码隐藏:

    public class Countries : IHttpHandler
        {
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "application/json";
    
                var cntries = new List<string>() {"Slovenia", "Italy", "Germany", "Austria"}; 
    
                JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
    
                context.Response.Write(jsSerializer.Serialize(cntries));
    
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    

    此示例使用 ASP.NET 3.5 及更高版本中提供的JavaScriptSerializer。如果您使用的是 asp.net 的情人版本 3.5 以上,您可以使用JSON.NET 将 typeahead 结果转换为 JSON 格式。

    【讨论】:

    • Default.aspx 在以“prefetch:”开头的行上缺少右引号
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 2016-04-03
    • 2015-01-21
    相关资源
    最近更新 更多