Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 625
Bhushan Firake Avatar asked Nov 29 '25 02:11

Bhushan Firake


1 Answers

Probably 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 a 'field' class

Or even something like:

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

Haven't tested the code though, just out of my head :)

like image 133
thaJeztah Avatar answered Nov 30 '25 16:11

thaJeztah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!