Autocomplete Textbox Using Database Return Value in ASP.NET Mvc3 Razor With Jquery


Description

In my previous related article I have explained how to use an autocomplete textbox using Jquery with a hardcoded value.

http://www.c-sharpcorner.com/UploadFile/b19d5a/autocomplete-textbox-in-razor-view-engine-using-jquery-in-as/

Here I will explain, when typing into a textbox, how the value will come from a database table.

In my application I have used the Entity Framework for database creation.

Now in my MVC3 application I have a model class named "student.cs" where I will store some student information.

    public class Student
    {
        public int StudentID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
 
    }


Also I have a controller class named "studentController.cs" under the controller folder.

Now for the studencontroller class I have an opening page in razor named "index.cshtml".

In this page I have a textbox where the user will enter the "firstname" of the student and it will give like autoextender features.

See the following code where I am catching the user data:

@using (Html.BeginForm())
{
    <p>
        Find by name: @Html.TextBox("SearchString")  
        <input type="submit" value="Search" /></p>
}

Now we have to handle the textbox enter event in our student controller class.

For that we have to write a particular ActionResult name "AutocompleteSuggestions" in our "studentController.cs" class.

See the following code:

public JsonResult AutocompleteSuggestions(string searchstring)
{
    private SchoolContext db = new SchoolContext();

    var suggestions = from s in db.Students
                              select s.FirstMidName ;
    var namelist = suggestions.Where(n => n.ToLower().StartsWith(searchstring.ToLower()));

    return Json(namelist, JsonRequestBehavior.AllowGet);
}


See here I have used "Jsonresult" instead of "ActionResult". That means the return data will be in a json format.

The searchstring is the user input text in the textbox.

Here my "SchoolContext" is the Entityframework database name.

After that I query the "Student" model class and get the firstname.

After that I query the "suggestions" variable with Lamdaexpression and check the "StartWith" method (marked as yellow) with our user given searchstring.

Finally we are returning with Jsonformat.

Next Step:

Now we have to write the Jquery code for the autocomplete extender property in to our "indesx.cshtml" file.

MVC3Rzr1.gif

Please see the following code:

<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {

        $("#SearchString").autocomplete({
            source: "/Student/AutocompleteSuggestions",
            minLength: 1,
            select: function (event, ui) {
                if (ui.item) {
                    $("#SearchString").val(ui.item.value);
                    $("form").submit();
                }
            }
        });
    });
</script>

That's it. Now after running the application it will look like the following image:

MVC3Rzr2.gif

I have typed "s" and it is displaying all students beginning with 's' in the first name in the autocomplete extender property.

This example is made of VS2010, with Entity Framework.

Conclusion

So in this article we have learned how to use an autocomplete textbox with a value coming from the database using Jquery.

So try this out…It's a cool feature.

Up Next
    Ebook Download
    View all
    Learn
    View all