Parse the JSON with jquery and add it to the autocomplete list of the textbox

I am trying to create an autocomplete textbox. My script is below on the 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:

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 like below:

[{"CountryId":"1","CountryName":"India"},
 {"CountryId":"2","CountryName":"Indonesia"}
]

      

I want to 1] parse this data and 2] add it to the textbox on the above browse page. How can i do this?

+3


source to share


2 answers


Perhaps a simpler solution:

$(function () {
    $('.field').keyup(function () {
        $.getJson("./js/" + $('.field').val(), function (result) {
            // result should contain the parsed JSON
        });
    });

});

      

Examples can be found here: http://api.jquery.com/jQuery.getJSON/

Note: The second selector for '.field' should probably be replaced with $ (this), val () will be retrieved for every tag with class 'field'



Or even something like:

    $.on('keyup', '.field', function () {
        $.getJson("./js/" + $(this).val(), function (result) {
            // result should contain the parsed JSON
        });
    });

      

Didn't check the code though, just out of my head :)

+1


source


Parse the returned string to make it an object, then iterate over the object somehow and insert the values ​​where you would like to insert them:



$(function() {
    $('.field').on('keyup', function() {
        $.ajax({
            url: "./js/" + this.value
        }).done(function(data) {
            var json = $.parseJSON(data);
            $.each(json, function(key, value) {
                 $(element).append(value);
            });
        });
    });
});

      

0


source







All Articles