1
嗨所有人都可以爲我提供一個很好的例子,說明如何在asp.net中使用Twitter Typeahead(http://twitter.github.io/typeahead.js/)和數據庫。Twitter TypeAhead with Asp .Net
感謝
嗨所有人都可以爲我提供一個很好的例子,說明如何在asp.net中使用Twitter Typeahead(http://twitter.github.io/typeahead.js/)和數據庫。Twitter TypeAhead with Asp .Net
感謝
在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格式返回數據這樣的:
Default.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;
}
}
}
此示例使用JavaScriptSerializer
這是在ASP.NET 3.5及更高版本。如果您使用的愛人版本超過3.5,您可以使用JSON.NET將預先結果轉換爲JSON格式。
感謝ashx的想法.. – MaxPayne
Default.aspx缺少以「prefetch:」開頭的行上的引號 – brainbolt