How to get Json Data from an external WEB API to an JQUery autosearch text box end point

Jose Daniel Navarro Brito 61 Reputation points
2025-01-10T16:24:18.3033333+00:00

Hi everybody:

I have an external minimal Web API that produces a JSON object ( array) as per below.

app.MapGet("/AsyncAutocompleteErf/{search}", async (IErvenRepository request,  string search) =>
{
    var data = await request.GetSearchedErfNumberAsync(search);
    if (data == null)
        return Results.NotFound("Sorry, there are not records");
    return Results.Ok(data);
}).WithName("AsyncAutocompleteErf");

The method executes an SQL procedure returning a JSon array with the following structure

[
  {
    "value": "1",
    "label": "15209 =>Gugulethu Infill Housing "
  }
]


Then, I have and end point application that calls the above API method as per below

   public async Task<string> AutoComplete(string search)
   {
       IEnumerable<AutoSearchViewModel> apiResponseBody = null;
       {
           var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");
           using (var response = await httpClient.GetAsync("AsyncAutocompleteErf/" + search))
           {
               if (response.IsSuccessStatusCode)
               {
                   
                   var content = await response.Content.ReadAsStringAsync();
                 
                   return (content);
                  
               }
           }
       }
       return null;
   }

Up to this point, I''m using ReadAsStringAsync the HTTp response ( the JSON array) to an string in order to "feed"the value, label items that the Jquery autocmplete drop down box needs ( my understanding).

Accordingly, I have a javascript function hooked up to this procedure.

<script type="text/javascript">
    $(function () {
        $("#txtCustomer").autocomplete({
             minLength: 2,
          
            source: function (request, response) {
                $.ajax({
                    url: '/Erf/AutoComplete/',
                    data: { "search": request.term},
                    dataType: "json",
                    type: "GET",
                    sucess:function(data)
                          {response((data));
                    },                       
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
        });
    });
</script>

When I run the Javascript function everything fires up and the HTTP response is of course a string with the following structure [{"value":"1","label":"15209 =>Gugulethu Infill Housing "}]

The autocomplete target doesn't load any data so I assume that converting the JSON array to a string is not the way to go. I tried to return a JSON via JSONResult Action Task ( see below) but the JSon response is like this => "[{\u0022value\u0022:\u00221\u0022,\u0022label\u0022:\u002215209 =\u003EGugulethu Infill Housing \u0022}]"

  [HttpGet]
  
   public async Task<JsonResult> AutoComplete(string search)
   {
       IEnumerable<AutoSearchViewModel> apiResponseBody = null;
       {
           var httpClient = _httpClientFactory.CreateClient("HousingWebAPI");
           using (var response = await httpClient.GetAsync("AsyncAutocompleteErf/" + search))
           {
               if (response.IsSuccessStatusCode)
               {
                   
                   var content = await response.Content.ReadAsStringAsync();
                 
                   return Json(content);
                  
               }
           }
       }
       return null;
   }

Can anybody assist me please? Also ..is it right to use GET instead of Post for the purpose of loading a jquery autocomplete text box?

Thanks in advance

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,730 questions
JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
1,020 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
361 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 69,121 Reputation points
    2025-01-10T17:25:46.89+00:00

    it you look at the response in the browser debug tools the json string is probably encoded, because the AutoComplete action returned a string that is converted to a json. for example:

    the string value [{"value":1}] when converted to json is: "[{\"value\":1}]"

    the method Json is expecting an object to convert, not a string that contain Json Data. you ned to return content of type "application/json".

           var content = await response.Content.ReadAsStringAsync();
           return Context(content,"application/json");
    

  2. SurferOnWww 3,696 Reputation points
    2025-01-11T06:23:24.1066667+00:00

    Are you saying that your Web API returns JSON string [{\u0022value\u0022:\u00221\u0022,\u0022label\u0022:\u002215209 =\u003EGugulethu Infill Housing \u0022}] although you are expecting [{"value":"1","label":"15209 =>Gugulethu Infill Housing "}] ?

    If so it is probably the result of Unicode Escape Sequence (UES). Please refer to the following Microsoft document:

    Serialization behavior

    "The default encoder escapes non-ASCII characters, HTML-sensitive characters within the ASCII-range, and characters that must be escaped according to the RFC 8259 JSON spec."

    The characters " and > in [{"value":"1","label":"15209 =>Gugulethu Infill Housing "}] belong to the HTML-sensitive characters within the ASCII-range. Therefore, they were converted to \u0022 and \u003E.

    UES is character expression in the form of \uxxxx where xxxx is Unicode of such character:

    enter image description here


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.