Wednesday 4 March 2015

Auto complete in MVC

autocomplete example
you have to add jquery libary file in bundle
  "~/Scripts/jquery-ui-1.8.24.js"


@model MvcApplication6.ViewModel.EMP

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>EMP</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.EID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EID)
            @Html.ValidationMessageFor(model => model.EID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.NAME)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NAME)
            @Html.ValidationMessageFor(model => model.NAME)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}



@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")


<script type="text/javascript">
    $(function () {


        $("#NAME").autocomplete({
            minLength: 0,
            source: '@Url.Action("Gets")',
            focus: function () {
            },
            select: function (event, ui) {
            }
        });


    });
</script>

}

controler

 public JsonResult Gets(string term)
        {
            using (TestEntities obj = new TestEntities())
            {
                return Json(obj.EMP1.Where(m => m.NAME.StartsWith(term)).Select(n => n.NAME).ToList(), JsonRequestBehavior.AllowGet);
            }
        }

No comments:

Post a Comment