I have a generic MVC aspnetcore setup, that pulls data from a local DB that is full with all USA zip codes, the state and city they are associated with. I am trying to pull back suggestion after say 3 digits are put in for what state they should be inferring and then to fill in the missing city after 5 digits are placed in the textbox. The issue that is baffling me is that within the javascript function data has the returned information. But that information is lost once the scope has left the function and also trying to set the value of another textbox to any of that information fails.
My view
@section Scripts{
<script src="Scripts/jquery-1.5.min.js" type="text/javascript"></script>
<script src="~/js/data.js" type="text/javascript"></script>
}
<div class="form-group">
<label asp-for="Zip" class="col-xs-2 control-label"></label>
<div class="col-xs-6">
<input id="Zip" asp-for="Zip" class="form-control" onkeyup="loadData()"/>
<span asp-validation-for="Zip" class="text-danger" />
</div>
</div>
My javascript file
function loadData() {
var str = $("#Zip").val();
if (str.length == 3){
$.get("/Localities/OnChange", { id: str }, function (data) {
$("#Code").val(data.code);
});
}
if (str.length == 5) {
$.get("/Localities/OnChange", { id: str }, function (data) {
$("#Boroughs").val(data.boroughs);
$("#City").val(data.city);
$("#Code").val(data.code);
$("#Country").val(data.country);
$("#County").val(data.county);
var temp = data.city;
});
}
}
My controller
[HttpGet]
public Localities OnChange(string id)
{
Localities temp = _context.Localities.FirstOrDefault(x => x.Zip.StartsWith(id));
var temp2 = JsonConvert.SerializeObject(temp);
return temp;
}