How to create AutoComplete TextBox In ASP.NET MVC 5

Here we are going to implement Auto Complete TextBox using Jquery and Mvc 5. Simply follow following steps.

Step 1: Go to Microsoft Visual Studio 2015 and create a new empty MVC 5 project.



Step 2: Now go to Controllers folder and add new empty HomeController.cs file. And paste following give code.




HomeController.cs
?

  
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using JQueryAutoComplete.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace JQueryAutoComplete.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(string keyword)
        {
            //This can be replaced with database call.
            List<Games> objGameList = new List<Games>
                (){
                new Games {Id=1,GameName="Cricket" },
                new Games {Id=2,GameName="Football" },
                new Games {Id=3,GameName="Chesh" },
                new Games {Id=4,GameName="VallyBall" },
                new Games {Id=5,GameName="Kabbadi" },
                new Games {Id=6,GameName="Hockey" }
            };
             
            var result = (from a in objGameList
                          where a.GameName.ToLower().StartsWith(keyword.ToLower())
                            select new { a.GameName });
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}

  

using JQueryAutoComplete.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace JQueryAutoComplete.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(string keyword)
        {
            //This can be replaced with database call.
            List<Games> objGameList = new List<Games>
                (){
                new Games {Id=1,GameName="Cricket" },
                new Games {Id=2,GameName="Football" },
                new Games {Id=3,GameName="Chesh" },
                new Games {Id=4,GameName="VallyBall" },
                new Games {Id=5,GameName="Kabbadi" },
                new Games {Id=6,GameName="Hockey" }
            };
            
            var result = (from a in objGameList
                          where a.GameName.ToLower().StartsWith(keyword.ToLower())
                            select new { a.GameName });

            return Json(result, JsonRequestBehavior.AllowGet);
        }


        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}


Step 3: Now add new class named Games.cs in Models folder. And add following code in to it.

Games.cs


?

  
1
2
3
4
5
6
7
8
namespace JQueryAutoComplete.Models
{
    public class Games
    {
        public int Id { get; set; }
        public string GameName { get; set; }
    }
}

  

namespace JQueryAutoComplete.Models
{
    public class Games
    {
        public int Id { get; set; }
        public string GameName { get; set; }
    }
}

Step 4: Go to BundleConfig.cs and comment following lines.
?

  
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System.Web;
using System.Web.Optimization;
namespace JQueryAutoComplete
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            //            "~/Scripts/jquery-{version}.js"));
            //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            //            "~/Scripts/jquery.validate*"));
            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));
            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));
            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

  
using System.Web;
using System.Web.Optimization;

namespace JQueryAutoComplete
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            //            "~/Scripts/jquery-{version}.js"));

            //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            //            "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

Step 5: Now move to Home in View view folder and replace the following code with Index.cshtml.
?

  
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@model JQueryAutoComplete.Models.Games
@{
    ViewBag.Title = "Home Page";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"> </script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#GameName").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { keyword: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.GameName, value: item.GameName };
                        }))
                    },
                    error: function () {
                        alert('something went wrong !');
                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <br />
        <br />
        <div class="form-group">
            <div class="col-md-12">
                <label for="games">Select Game :-</label>
                @Html.EditorFor(model => model.GameName, new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>
    </div>
}

  
@model JQueryAutoComplete.Models.Games
@{
    ViewBag.Title = "Home Page";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"> </script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#GameName").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { keyword: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.GameName, value: item.GameName };
                        }))
                    },
                    error: function () {
                        alert('something went wrong !');
                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <br />
        <br />
        <div class="form-group">
            <div class="col-md-12">
                <label for="games">Select Game :-</label>
                @Html.EditorFor(model => model.GameName, new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>

    </div>
}

Step 6: Compile the code and runt the application. You can now use AutoComplete in your application.



Note : You need to use the Jquery library to perfom this example.

How to install mongoDB


  1. Go to Downloads - MongoDB.
  2. Find the Current Stable Release of Community Server, select the latest 64-bit / 32-bit version in the Windows column. Download, then run the MSI installer.
  3. MongoDB is typically installed in C:\Program Files\MongoDB. Search for Environment Variables on the desktop and add the MongoDB binaries path to the PATH variable. For example, you might find the binaries at C:\Program Files\MongoDB\Server\3.4\bin on your machine.
4.    Create MongoDB data and log directories in the data disk (such as drive F:) you created in the preceding steps. From Start, select Command Prompt to open a command prompt window. Type:
 C:\> F:
 F:\> mkdir \MongoData
 F:\> mkdir \MongoLogs
5.    To run the database move to the C:\Program Files\MongoDB\Server\3.4\bin path, run:
C:\Program Files\MongoDB\Server\3.4\bin> mongod --dbpath F:\MongoData\ --logpath F:\MongoLogs\mongolog.log
All log messages are directed to the F:\MongoLogs\mongolog.log file as mongod.exe server starts and preallocates journal files. It may take several minutes for MongoDB to preallocate the journal files and start listening for connections. The command prompt stays focused on this task while your MongoDB instance is running.
6.    To start the MongoDB administrative shell, open another command window from Start and type the following commands:
 C:\> cd \my_mongo_dir\bin 
 C:\my_mongo_dir\bin> mongo 
 >db 
 test
 > db.foo.insert( { a : 1 } ) 
 > db.foo.find() 
 { _id : ..., a : 1 } 
 > show dbs 
 ... 
 > show collections 
 ... 
 > help 
The database is created by the insert.
7.    Alternatively, you can install mongod.exe as a service:
 C:\> mongod --dbpath F:\MongoData\ --logpath F:\MongoLogs\mongolog.log --logappend  --install
A service is installed named MongoDB with a description of "Mongo DB". The --logpath option must be used to specify a log file, since the running service does not have a command window to display output. The --logappend option specifies that a restart of the service causes output to append to the existing log file. The --dbpath option specifies the location of the data directory. For more service-related command-line options, see Service-related command-line options.
     To start the service, run this command:
C:\> net start MongoDB
  1. Now that MongoDB is installed and running.

Happy coding…J