1

I'm working on autocomplete JQuery function to populate student names in the text box. I've utilized every related JQuery library to make the autocomplete function work. When i press F12, it always throws an error which is "autocomplete is not a function". Below is my code that I'm running.

StudentBatch.cshtml

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<div class="form-group">
    <div class="col-md-12">
        @Html.EditorFor(model => model.StudentName, new { id = "StudentName" })

    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        alert("This is autocomplete function");
    });
    $(document).ready(function () {
        $("#StudentName").autocomplete({
            //autocomplete: {
            //    delay: 0,
            //    minLength: 1,
            source: function (request, response) {
                $.ajax({
                    url: "/Student/Create",
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        try {
                            response($.map(data, function (item) {
                                return { label: item.StudentName, value: item.StudentName };
                            }))
                        } catch (err) { }
                    }
                })
            },
            messages: {
                noResults: "jhh", results: "jhjh"
            }

        });

    });
</script>

StudentController.cs

[HttpPost]
public JsonResult Create(string Prefix)
{
    CreateUser user = new CreateUser();
    string stdid = "fae30ef0-08b2-4490-a389-3c8eb0a7cc53";
    var StudentList = user.GetAllUsers().ToList().Where(u => u.FirstName == Prefix && u.usertypeid == stdid).ToString();
    return Json(StudentList, JsonRequestBehavior.AllowGet);
}
10
  • Remove the ToString() from your query. (an as a side note, remove new { id = "StudentName" } in your EditorFor() - that does not add an id attribute, and the method already adds id="StudentName" anyway) Commented Dec 11, 2017 at 6:33
  • And there is no point returning all the properties of Student when you never use them - just use a .Select(x => x.StudentName) and use return { label: item, value: item }; Commented Dec 11, 2017 at 6:35
  • Point noted. The actual issue still occurring which is on autocomplete method. Commented Dec 11, 2017 at 6:39
  • That is because your scripts are not loaded correctly. Possibly due to the issue in this answer Commented Dec 11, 2017 at 6:40
  • Well I've checked that link and tried something, yet nothing happened. To be noticed when i get into the console in IE, i get to see two similar files of jquery. I don't know why it is loading two similar files. Commented Dec 11, 2017 at 7:00

1 Answer 1

0

I have created similar demo which you are creating.

Model

public class CreateUser
 {
     public string StudentName { get; set; }
     public string StudentId { get; set; }
 }

Controller

public class StudentController : Controller
{
    // GET: Student
    public ActionResult Create()
    {
        return View();
    }


    [HttpPost]
    public JsonResult Create(string prefix)
    {
        List<CreateUser> studentList = new List<Models.CreateUser>()
        {
            new CreateUser { StudentId = "1" , StudentName = "Student1"},
            new CreateUser { StudentId = "2" , StudentName = "Student2"},
            new CreateUser { StudentId = "3" , StudentName = "Student3"},
            new CreateUser { StudentId = "4" , StudentName = "Student4"},
            new CreateUser { StudentId = "5" , StudentName = "Student5"},
            new CreateUser { StudentId = "6" , StudentName = "Student6"},
            new CreateUser { StudentId = "7" , StudentName = "Student7"},
        };

        var searchlist = (from student in studentList
            where student.StudentName.Contains(prefix)
            select student).ToList();

        return Json(searchlist, JsonRequestBehavior.AllowGet);
    }
}

View

@model WebApplication6.Models.CreateUser
@{
    Layout = null;
}
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
<style>
    .ui-autocomplete {
        max-height: 100px;
        overflow-y: auto;
        /* prevent horizontal scrollbar */
        overflow-x: hidden;
    }
    /* IE 6 doesn't support max-height
     * we use height instead, but this forces the menu to always be this tall
     */
    * html .ui-autocomplete {
        height: 100px;
    }

    .ui-autocomplete-input {
        width: 300px;
    }
</style>

<div class="form-group">
    <div class="col-md-12">
        @Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
    </div>
</div>

<script type="text/javascript">

    $(document).ready(function () {
        $("#StudentName").autocomplete({
            //autocomplete: {
            //    delay: 0,
            //    minLength: 1,
            source: function (request, response)
            {
                $.ajax({
                    url: "/Student/Create",
                    type: "POST",
                    dataType: "json",
                    data: { prefix: request.term },
                    success: function(data) {
                        try {
                            response($.map(data,
                                function (item)
                                {
                                    return { label: item.StudentName, value: item.StudentName };
                                }));
                        } catch (err) {
                        }
                    }
                });
            },
            messages:
                {
                noResults: "jhh", results: "jhjh"
            }

        });

    });
</script>

Output

enter image description here

Sign up to request clarification or add additional context in comments.

8 Comments

Same error occurring at my side "Failed to load resource: the server responded with a status of 500 (Internal Server Error)"
Alright now, the problem was with the name of the Controller action. As i changed the name the code started working and displayed the desired result.
Just a quick question before marking it an answer, I previously added a linq query to display the name from the database. Please suggest if the particular linq statement is right or not.
it is correct but you can also try Contains in where clause.
@user100020 is there anything else
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.