3

I need to create an autocomplete textbox to populate customer names in an ASP.Net MVC application. The jQuery code in my view is as follows:

$(document).ready(function() {
    $("input#bldCustomerName").autocomplete({
        source: '<%= Url.Action("ListCustomers","Build") %>'
    });
});

My controller action is:

public ActionResult ListCustomers(string term)
    {
        IList<HSTrader> lstTraders = new List<HSTrader>();
        Build objBld = new Build();
        string trdrType = Resources.Resource.TraderTypeCustomer;
        int trdrTypeId = objBld.GetTraderTypeByTraderTypeName(trdrType).Id;
        lstTraders = objBld.GetTradersByTraderType(trdrTypeId);

        var results = from m in lstTraders
                      where m.TraderName.StartsWith(term)
                      select m.TraderName; //new { label = m.TraderName, id = m.Id };

        return Json(results.ToArray(), JsonRequestBehavior.AllowGet);
    }

On keypress the controller action is executed, but the list doesn't appear under the textbox. What is wrong with my implementation?

3
  • 2
    Are you getting any errors in the console/firebug? Commented Nov 24, 2011 at 9:22
  • Ohh sorry its a case of case-sensitivity. Its giving proper outcome. Commented Nov 24, 2011 at 10:00
  • You may want to consider the Autocomplete helper form awesome.codeplex.com Commented Jan 24, 2012 at 20:24

2 Answers 2

1
 $(document).ready(function () {
            $('input#bldCustomerName').autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Build/ListCustomers', type: 'Get', dataType: 'json',
                        data: { term: request.term, maxResults: 10 },
                        success: function (data) {
                            response($.map(data, function (item) {
                                return { label: item.TraderName, value: item.TraderName, id: item.TraderName }

                                //return { label: item.d, value: item.d, id: item.d } 
                                //If it does not work then use this line. comment above line. it is for single dimension array (only one column.).
                            }))
                        }
                    });
                },
                select: function (event, ui) {

                }
            });
        });






        //BuildController
        [HttpGet]
        public JsonResult ListCustomers(string term, int maxResults)
        {
            IList<HSTrader> lstTraders = new List<HSTrader>();
            Build objBld = new Build();
            string trdrType = Resources.Resource.TraderTypeCustomer;
            int trdrTypeId = objBld.GetTraderTypeByTraderTypeName(trdrType).Id;
            lstTraders = objBld.GetTradersByTraderType(trdrTypeId);

            var results = from m in lstTraders
                          where m.TraderName.StartsWith(term)
                          select m.TraderName; //new { label = m.TraderName, id = m.Id };

            return Json(results.Take(maxResults).ToList(), JsonRequestBehavior.AllowGet);
        }
Sign up to request clarification or add additional context in comments.

Comments

0

Hope this helps someone...

I had to add jquery-ui libraries and stylesheets because they didn't come with VS2013 Scripts template. Here's an example of autocomplete with db query and TextBoxFor that worked for me:

WordListController.cs:

public ActionResult Test2(MyModel vm)
{
    return View(vm);
}
public JsonResult AutoComplete(string search)
{
    var result = (from r in db.Words
                  where r.Word.ToLower().StartsWith(search.ToLower())
                  select r.Word).Take(10).ToArray();

    return Json(result, JsonRequestBehavior.AllowGet);
}

Test2.cshtml:

@{
    ViewBag.Title = "test2";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/jqueryuicss")

@model  WLWeb.Models.MyModel

<h2>test2</h2>

<script>

        $(function () {
            $('#tags').autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '@Url.Action("AutoComplete", "WordList")',
                        dataType: "json",
                        contentType: 'application/json, charset=utf-8',
                        data: {
                            search: $("#tags").val()
                        },
                        success: function (data) {

                            response($.map(data, function (item) {
                                return {
                                    label: item
                                };
                            }));
                        },
                        error: function (xhr, status, error) {
                            alert(error);
                        }
                    });
                },
                minLength: 2
            });
        });

</script>

    @Html.TextBoxFor(x => Model.SelectionModel.SearchString, new { @id = "tags", style = "width:120px;" })

Layout.csthml:

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")

</head> 
<body>
...
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

BundleConfig.cs:

...
        bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                    "~/Scripts/jquery-ui-{version}.custom.js"));

        bundles.Add(new StyleBundle("~/Content/jqueryuicss").Include(
                  "~/Content/jquery-ui-{version}.custom.css"));   

Comments

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.