Autocomplete not working - Asp . net MVC

Asked

Viewed 105 times

0

Good morning guys, I’m having trouble implementing a field with autocomplete in an Asp . Net MVC application. The problem is this, using an Ajax I can go to my controller and search for results of the query, however, in the return where to display the result it always falls in the "error" field, showing Json in an "Alert" as I will show below:

$(document).ready(function () {
    $('#Cd_Cod_Produto').keypress(function () {
        $('#Cd_Cod_Produto').autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Estoque/GetAutoComplete",
                    type: "POST",
                    dataType: "application/json",
                    data: { term: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.Name,
                                value: item.Value                                  
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }                   
                });
            }
        });

    });

});

As you can see, if an error occurs, an Alert is displayed with the search result, and always falls into this Alert. My Controller is like this:

 public ActionResult GetAutoComplete(string term)
    {
        EstoqueDAO dao = new EstoqueDAO();

        List<Autocomplete> lista = dao.BuscaResultados(term);

        dao.Dispose();

        string json = JsonConvert.SerializeObject(lista);

        return Json(json, JsonRequestBehavior.AllowGet);
    }

and this is the model I’m using only for testing:

 public class Autocomplete
{
    public string Name { get; set; }
    public string Value { get; set; }

}

The database search is returning values correctly, I believe that is not the problem. inserir a descrição da imagem aqui

As you can see in the image is what happens with the return of the function. Does anyone have any hint or hint of where I’m going wrong? Thanks for your help.

Sincerely yours,

Updating:

I changed the script to this shape:

$(document).ready(function () {
    $('#Cd_Cod_Produto').keypress(function () {
        $('#Cd_Cod_Produto').autocomplete({
            source: function () {
                $.get(url, { term: $('#Cd_Cod_Produto').val() }, function (data) {
                    $.map(data, function (item) {
                        return {
                            label: item.Name,
                            val: item.Value

                            //console.log(item.Name);

                        }                              
                    });

                });
            }
        });

    });
});

This way it looks for the results in the controller, but has not yet shown anything in the autocomplete. If you remove the comments from the "/console.log(item.Name)" line it normally displays the results on the console.

  • Take out that code snippet string json = JsonConvert.SerializeObject(lista); and returns like this: return Json(lista, JsonRequestBehavior.AllowGet);

  • Hi @Pedropaulo, thanks for replying. I did what you said, but it keeps falling on Alert, the difference is that the returned Json looks like this: [{"Name":"ES001","Value":"ES001"},{"Name":"ES002","Value":"ES002"},{"Name":"ES003","Value":"ES003"},{"Name":"ES004","Value":"ES004"}]...without the """""" as it was being shown earlier.

  • Another observation, this method should be GET, semantically makes more sense. Even the name of your back-end method starts with Get.

  • @Peter Paul, I changed the methods to become more semantic, but the problem remains.

1 answer

0

change that part:

 function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.Label,
                                value: item.Value                                  
                            }
                        }))

for:

function (data) {
 $.map(data, function (item) {
  return {
       label: item['Name'],
       value: item['Value']   
      //ou
      //label: item.Name,
      //value: item.Value                                 
   }
   }

Functional example:

var lis = [{'Name': '1', 'Value': 'A'}, {'Name': '2', 'Value': 'B'}, {'Name': '3', 'Value': 'C'}, {'Name': '4', 'Value': 'D'}];


var x = $.map(lis, function(item){
     return {
       label: item.Name,
      value: item.Value                              
   }
});

console.log(x);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • thanks for your reply, it was an error of a previous attempt, already switched to "Name" and still not working.

  • @Q.Wesley changed the answer.

  • I made the changes you said, it didn’t work, keep falling in Alert.

  • could test the return of Data only, something like Function (data) { Return data;}

  • and to be sure of the result create a var to receive the ajax, and then use in the source

  • I did the tests you asked, took the return of ajax and played in a variable, and asked to display the value on the console and in an "Alert", the result was "Undefined" in both cases. the code I used was this:

  • Function testAjax() { $.ajax({ url: "/Stock/Getautocomplete", type: "GET", dataType: "application/json", date: { term: '00' }, Success: Function (date) { Return data; } }); }; Function Test() { var return = testAjax(); Alert(return); console.log(return); };

  • you forgot the Return here Function testAjax() { Return $.ajax...

  • put a breakpoint on the web console and see if the data is coming into the variable.

  • i did another function, modified a few things, stayed that way: Function testAjax() { var url = "/Stock/Getautocomplete"; $.get(url, { term: '00' }, Function (date) { //console.log(data); $.map(data, Function(item) { console.log(item.Name); }); }); }; .

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.