jqueryasp.net-mvcjquery-autocomplete

jquery autocomplete shows id when selecting a text


in my application when selecting a value from dropdown list of autocomplete textbox, it shows only id not value my code is below

[AcceptVerbs(HttpVerbs.Post)]
    public JsonResult Autocomplete(string term)
    {
        List<DemoModel> demo = new List<DemoModel>();
        demo.Add(new DemoModel(1, "one"));
        demo.Add(new DemoModel(2, "two"));
        return Json(demo, JsonRequestBehavior.AllowGet);
    }

my view

$(document).ready(function () {


    $("#PassId").autocomplete({
        source: function (request, response) {

            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url: "@(Url.Action("Autocomplete", "Home"))",
                data: { "term": request.term },
                success: function (data) {


                    response($.map(data, function (item) {

                        return { label: item.name, value: item.id };
                    }))
                },
                select: 
        function (event, ui) {

            $("#PassId").val(ui.item.label);
            return false;
        },

                focus: function(event, ui) {

                    $("#PassId").val(ui.item.label);
                    return false;
                }
            });
        }
    });
});

where am I doing wrong? thanks.


Solution

  • i guess before this :

    }, // <-----before this
    select:
    

    You have to close the ajax method:

      }); //<----this closing of ajax is missing.
    },
    select:
    

    Or i would say there are syntax errors, check this:

    $("#PassId").autocomplete({
      source: function(request, response) {
    
        $.ajax({
              async: false,
              cache: false,
              type: "POST",
              url: "@(Url.Action(" Autocomplete ", " Home "))",
              data: { "term": request.term },
              success: function(data) {
                response($.map(data, function(item) {
                  return {
                    label: item.name,
                    value: item.id
                  };
                }))
              });
          },
          select: function(event, ui) {
    
            $("#PassId").val(ui.item.label);
            return false;
          },
    
          focus: function(event, ui) {
    
            $("#PassId").val(ui.item.label);
            return false;
          } // <---you had a wrong closing here.
      }
    });