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