Elena E
Elena E

Reputation: 85

Autocomplete ASP.NET MVC with JSON

I am trying to make an autocomplete functionality for my page. I have a textbox and I would like to make suggestions from my database.

I have this JsonResult in my controller:

public JsonResult ItemAutocomplete(string term)
{
    var result = _db.SelectTable("SELECT [i].[Name] from [dbo].[Item][i] WHERE [i].[Name] LIKE @0", SqlDb.Params(term +"%"));
    return Json(result, JsonRequestBehavior.AllowGet);
}

and in my view:

@Scripts.Render("~/bundles/jqueryui")
<h2>jQuery AutoComplete</h2>
<script>
      $(function () {
           $('#tags').autocomplete({
              source: function (request, response) {
                  $.ajax({
                      url: '@Url.Action("ItemAutocomplete")',
                      extraParams: { term: $('#tags').val(), 
                      dataType: "json",
                      contentType: 'application/json, charset=utf-8',
                      data: {
                          term: $("#tags").val()
                      },
                      success: function (data) {

                          response($.map(data, function (item) {
                              return {
                                  label: item
                              };
                          }));
                      },
                      error: function (xhr, status, error) {
                          alert(error);
                      }
                  });
              },
              minLength: 2
          });
      });

</script>

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags" />
</div>

The problem is that my ItemAutocomplete jsonResult always receives a null param... even if I call it directly from localhost, like this: "localhost/Appointment/ItemAutocomplete/item1".

Upvotes: 2

Views: 1323

Answers (1)

chirag
chirag

Reputation: 123

Use (request.term) below

data: { term: request.term }

instead of

data: { term: $('#tags').val() }

In Autocomplete Text box, search string detect by "request.term".

Upvotes: 3

Related Questions