Reputation: 103
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.
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
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
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