Friday 29 August 2014

Autocomplete TextBox in MVC

RAVEntities  is a Entity Model

Controller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoComplete.Models;

namespace AutoComplete.Controllers
{
    public class AutoCompleteController : Controller
    {
        //
        // GET: /AutoComplete/

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult getData(string term) {
            var result = new List<KeyValuePair<string, string>>();
            RAVEntities re=new RAVEntities();
            IList<vehicle> objVehicleList= (from data in re.vehicles
                               select data).ToList();
            foreach (var item in objVehicleList)
            {
                result.Add(new KeyValuePair<string, string>(item.Vehicle1, item.Vehicle1.ToString()));
            }
            var result3 = result.Where(s => s.Value.ToLower().Contains(term.ToLower())).Select(w => w).ToList();
            return this.Json(result3, JsonRequestBehavior.AllowGet);
        }

    }
}

View Code

@{
    ViewBag.Title = "Index";
    Layout = null;
}
@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")

<script type="text/javascript">
    $(document).ready(function () {
        $("#Country").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/AutoComplete/getData",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Key, value: item.Value };
                        }))

                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>
@Html.TextBox("Country")
<input id="tags" type="text" />

No comments:

Post a Comment