以下jQuery自動完成代碼未在MVC3中顯示結果。當我調試代碼時,我可以看到它正確調用了QuickSearchByLastName。有人可以告訴我,如果我的代碼不正確? (我也試過用jquery-1.6.2.min.js沒有運氣)謝謝!MVC3 jQuery自動完成未顯示結果
Index.cshtml:
@using (Ajax.BeginForm(new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "results"
}
))
{
<input type="text" name="q" data-autocomplete="@Url.Action("QuickSearchByLastName","Search")" />
}
<div id="results" >
</div>
----------------------------------------------------------------
Search Controller:
public ActionResult QuickSearchByLastName(string term)
{
using (var context = new CSCContext())
{
var searchResults = context.Students
.Where(s => s.LastName.Contains(term) && s.IsActive == true)
.Take(10)
.Select(s => new { label = s.LastName });
return Json(searchResults, JsonRequestBehavior.AllowGet);
}
}
_Layout.cshtml:
@Content.Script("jquery-1.4.4.min.js", Url)
@Content.Script("jquery.unobtrusive-ajax.min.js", Url)
@Content.Script("jquery-ui.min.js", Url)
@Content.Script("jquery.validate.min.js", Url)
@Content.Script("jquery.validate.unobtrusive.min.js", Url)
@Content.Script("CSC.js", Url)
@RenderSection("scripts", false)
CSC.js
$(document).ready(function()
{
$(":input[data-autocomplete]").each(function()
{
$(this).autocomplete({
source: $(this).attr("data-autocomplete")
}
);
});
});
下面的代碼解決了該問題:
public ActionResult QuickSearchByLastName(string term)
{
var context = new CSCContext();
try
{
var searchResults = context.Students
.Where(s => s.LastName.Contains(term) && s.IsActive == true)
.Take(10)
.Select(s => new { label = s.LastName });
return Json(searchResults.ToList(), JsonRequestBehavior.AllowGet);
}
finally
{
context.Dispose();
}
}
送你的確可以使用JSON用於自動完成插件 –
插件或1.8用戶界面功能? – Buildstarted