I am trying to build an autocomplete textbox. My script is as below in Razor View page:
@model AutoComplete.Models.Country
@{
ViewBag.Title = "Index";
}
@Scripts.Render("~/bundles/jquery")
<h2>Index</h2>
@Html.TextBoxFor(m => m.CountryName, new { Class = "field" })
<div class="keys"></div>
<script>
$(function () {
$('.field').keyup(function () {
$.ajax({
url: "./js/" + $('.field').val(),
success: function (result) {
}
});
});
});
</script>
My controller method is:
public ActionResult SearchByKey(string keyword)
{
CountryContext db = new CountryContext();
var result= db.Countries.Where(x => x.CountryName.Contains(keyword));
return Json(result , JsonRequestBehavior.AllowGet);
}
My controller returns Json data as below:
[{"CountryId":"1","CountryName":"India"},
{"CountryId":"2","CountryName":"Indonesia"}
]
I want to 1]parse this data and 2] append it to the textbox in the above view page. How can I do this?
dataType: "json"to your$.ajax()parameters. That tells the function to expect a JSON formatted response.resultin thesuccesscallback?alert ($.parseJSON(result));and tell us the result