0

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

Community
  • 1
  • 1
Tommaso
  • 1
  • 2

2 Answers2

0

You can set breakpoints on GetJsonUsers and trace through to an error. You can also see what is coming back to your browser using f12.

Ross Bush
  • 14,648
  • 2
  • 32
  • 55
0

Do as follows:

       $('#txtListUsers').autocomplete({
          source:function( request, response ) {
              $.ajax({
              url: "@Url.Action("YourActionName","YourControllerName")",
              dataType: "json",
              data: {},
              success: function( data ) {
                 response( $.map( data, function( item ) {
                    return {
                       label: item.name,
                       value: item.name
                           }
                         }));
              }
             });
             },
           minLength: 2
       });
Jatin patil
  • 4,252
  • 1
  • 18
  • 27