3

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?

8
  • 1
    You can cover the parsing aspect by adding dataType: "json" to your $.ajax() parameters. That tells the function to expect a JSON formatted response. Commented Jan 27, 2013 at 11:44
  • @diggersworld No effect after adding datatype Commented Jan 27, 2013 at 11:51
  • What's the value of result in the success callback? Commented Jan 27, 2013 at 11:54
  • @Alexander When I alert result , it says [object Object], [object Object] Commented Jan 27, 2013 at 11:55
  • try alert ($.parseJSON(result)); and tell us the result Commented Jan 27, 2013 at 11:58

2 Answers 2

1

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

I wanted to illustrate usage of .getJson as alternative to .ajax, in order to don't have to specify content-types etc. Furthermore, the answer by Simon below doesn't really make sense; the data should not need to be parsed (parseJSON) for each element in the array
0

Parse the returned string to make it an object, then somehow iterate over the object and insert the values where you'd like to have them inserted :

$(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);
            });
        });
    });
});

11 Comments

It shows an error in firebug TypeError: object is null [Break On This Error] length = object.length,
It sounds like you are not returning proper formatted JSON from the serverside.
@adeneo $(element).append(value) should probably be $(element).append(value.CountryName); or something alike?
@BhushanFirake if you put console.log(data); inside the 'done' callback, does it output a JSON array/object or a string?
@thaJeztah - You're probably right, but it was meant more as a guide on how to iterate and insert values, as I'm not sure the OP really knows what is returned here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.