I have implemented an autocomplete in my app for retrive a list of users, but the list is not displaying when I search a user.
In my _Layout.cshtml:
<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-2.0.3.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.10.3.js" type="text/javascript"></script>
In my View:
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#txtListUsers').autocomplete({
source: '@Url.Action("GetJsonUsers","GestioneLega")',
minLength: 2
});
});
})
</script>
...
<input type="text" id="txtListUsers" />
My Action:
public JsonResult GetJsonUsers(string term)
{
var users = GestServices.GetUsersForAutocomplete(term);
return Json(users, JsonRequestBehavior.AllowGet);
}
Get data:
public static object GetUsersForAutocomplete(string searchTerm)
{
object users = null;
using (var db = new FriendsContext())
{
users = from cust in db.Users.Where(c => c.UserName.StartsWith(searchTerm))
select cust.UserName;
}
return users;
}
The function GetJsonUsers not works: doing more tests, I noticed that in GetUsersForAutocomplete function, the variable "users" is filled only in the using scope. if I do an immediate control on users out of using scope, obtain: The operation cannot be completed because the DbContext has been disposed
I solved this problem by following this discussion The operation cannot be completed because the DbContext has been disposed error