SIGN UP MEMBER LOGIN:    
ARTICLE

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

Posted by Shirsendu Nandi Articles | ASP.NET MVC with C# February 02, 2012
In this article I will describe how to use an autocomplete textbox with a value coming from a database using Jquery.
Reader Level:
Download Files:
 

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.

Login to add your contents and source code to this article
share this article :
post comment
 

public JsonResult AutocompleteSuggestions(string searchstring) // (string term) { code here } Action needs to map to the parameter 'term'.

Posted by Renato Cantarino Mar 12, 2012

Very useful article.

Posted by Abhi Kumar Feb 03, 2012

Very useful..thank you for posting

Posted by Sonakshi Singh Feb 02, 2012

Hi Shirsendu. You have presented your article very nicely.

Posted by Monika Arora Feb 02, 2012
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor