Ahmed Hossam Alhansy
Ahmed Hossam Alhansy

Reputation: 103

Autocomplete Textbox from database MVC 5

I have my textboxfor field which select the data from role table from the database i need this textboxfor field make a autocomplete with starting character.

Sample:

MVC code:

This JsonResult in the UsersControl

 public JsonResult GetRoles(string Prefix)
    {
        var RoleListVal = db.Roles.Where(r => r.Deleted == false)
            .Where(r => r.Name.ToUpper().StartsWith(Prefix))
            .Select(r => new { Name = r.Name, ID = r.RoleID }).Distinct().ToList();
        return Json(RoleListVal, JsonRequestBehavior.AllowGet);
    }

cshtml Code:

This the JS and the HTML5 TextBoxFor:

$("#keywords-manual").autocomplete({
        source: "/Users/GetRoles",
        minLength: 1
    })
<div class="form-inline">
            @Html.Label("Role :")
            @Html.TextBoxFor(model => model.Roles.FirstOrDefault().Name, new { @class = "form-control", @id = "keywords-manual" })
</div>

I don't why isn't working!

Upvotes: 0

Views: 864

Answers (2)

Divyang Desai
Divyang Desai

Reputation: 7866

Here your controller side method looks good.

But issue is while you calling method.

    $("#keywords-manual").autocomplete({
        source: function (request, response) {
            $.ajax(
                    {
                        type: "POST",
                        url: '@Url.Action("GetRoles","Users")',
                        data: { Prefix: $('#keywords-manual').val() },
                        dataType: "json",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    value: item.Name,
                                    description: item
                                }
                            }))
                        },
                        error: function (error) {
                            console.log(error);
                        }
                    });
        },
        minLength: 1,
        select: function (event, ui) {

        }
    });

Upvotes: 2

Haitham Shaddad
Haitham Shaddad

Reputation: 4456

This is how you configure the Autocomplete plug in

On HTML Side:

$(function () {
            $("#keywords-manual").autocomplete({
                source: "@Url.Action("GetRoles","Users")",
                minLength: 1
            })
                   });

On the controller side:

public JsonResult GetRoles(string term)
    {
        var RoleListVal = db.Roles.Where(r => r.Deleted == false)
            .Where(r => r.Name.ToUpper().StartsWith(term))
            .Select(r => new { label = r.Name, id = r.RoleID,value=r.RoleID }).Distinct().ToList();
        return Json(RoleListVal, JsonRequestBehavior.AllowGet);
    }

Upvotes: -1

Related Questions