user1726549
user1726549

Reputation:

Autocomplete from database in MVC 5?

I have a model called Service, which includes a few fields, but the most important one for me is the ServiceName field. I have the view shown below:

@using (Html.BeginForm("Test", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new request.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.ServiceName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.ServiceName, new { @class = "form-control", @id = "keywords-manual" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Submit!" />
        </div>
    </div>
}

So, the point is that, when the user starts typing the service name, after 2 letters, I want to show the user suggestions, and use the autocomplete. I have already included the jQuery UI, and it works all fine, if I provide the autocomplete source manually as a JS array. But, I want the source to be read from the database. For this reason, I created the function below:

        public JsonResult GetServiceNames()
        {
            string keywords;
            var results = db.Services.Where(s => keywords == null || s.ServiceName.ToLower().Contains(keywords.ToLower())).Select(x => new { id = x.ServiceID, value = x.ServiceName }).Take(5).ToList();

            return results;
        }

Then in my JS part, I have the following code:

$("#keywords-manual").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "Home/GetServiceNames",
                data: "{ 'keywords': '" + request.term + "' }",
                dataType: 'json',
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) { return data; },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.value,
                            value: item.value,
                            id: item.id
                        }
                    }))
                }
            });
        },
        minLength: 2
    });

I cannot even test this code segments, while I have an error message at my GetServiceNames() function. I get a message at the return statement saying: Cannot explicitly convert type List<AnonymousType> to JsonResult

If someone can help me solve this problem, and also tell me whether my logic for autocomplete from database is correct (if not, please provide corrections), then I would be glad.

Upvotes: 0

Views: 7026

Answers (1)

DavidG
DavidG

Reputation: 118977

There's a few things wrong here. To fix the error message, you need to convert your result to Json like this:

return Json(results);

Additionally you are not passing anything into the action. Change the action to this:

public JsonResult GetServiceNames(string term)
{
    var results = db.Services.Where(s => term == null || s.ServiceName.ToLower().Contains(term.ToLower())).Select(x => new { id = x.ServiceID, value = x.ServiceName }).Take(5).ToList();

    return Json(results, JsonRequestBehavior.AllowGet);
}

Finally, your jQuery doesn't need to POST this request so I would change it to a GET. Overall, I would suggest changing your jQuery to something like this to test:

$("#keywords-manual").autocomplete({
  source: "/Home/GetServiceNames",
  minLength: 2
})

Upvotes: 3

Related Questions