AutoComplete TextBox In ASP.NET MVC Using Json Data

In many application we need to allow user to select data from master details such city list , country list or any other , Usually dropdownlist is used to allow to choose details from multiple list of records but if records are huge this drop down list approach will be fail So to allow user to pop up the list as per their search term then Autocomplete textbox is used which is proper approach . In this article we will implement auto complete textbox with the help of jQuery UI library from database with json data. So let us implement this requirement step by step,
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
  3. Choose MVC empty application option and click on OK
Step 2: Add model class.

Right click on Model folder in the created MVC application and add class named CityModel and right the following line of code,

CityModel.cs
public class City  
  {  
      public int Id { get; set; }  
      public string Name { get; set; }  
  
  }  
Step 3: Add user and admin controller

Right click on Controller folder in the created MVC application and add the controller class as:

Now after selecting controller template, click on add button then the following window appears,



Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class to bind and create the generic list from model class as in the following,

HomeController.cs
using System.Collections.Generic;  
using System.Linq;  
using System.Web.Mvc;  
using AutoCompleteInMVCJson.Models;  
namespace AutoCompleteInMVCJson.Controllers  
{  
    public class HomeController : Controller  
    {  
        // GET: Home  
        [HttpGet]  
        public ActionResult Index()  
        {  
            return View();  
        }  
        [HttpPost]  
        public JsonResult Index(string Prefix)  
        {  
            //Note : you can bind same list from database  
            List<City> ObjList = new List<City>()  
            {  
  
                new City {Id=1,Name="Latur" },  
                new City {Id=2,Name="Mumbai" },  
                new City {Id=3,Name="Pune" },  
                new City {Id=4,Name="Delhi" },  
                new City {Id=5,Name="Dehradun" },  
                new City {Id=6,Name="Noida" },  
                new City {Id=7,Name="New Delhi" }  
  
        };  
            //Searching records from list using LINQ query  
            var CityName = (from N in ObjList  
                            where N.Name.StartsWith(Prefix)  
                          select new { N.Name });  
            return Json(CityName, JsonRequestBehavior.AllowGet);  
        }  
    }  
}  
In the above code, instead of going to database for records we are creating the generic list from model class and we will fetch records from above generic list.

Step 4:
Reference jQuery UI css and js library reference as there are many ways to add the reference of jQuery library into the our project. The following are some methods:
  • Using NuGet package manager , you can install library and reference into the project
  • Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
  • Download jQuery files from jQuery official website and reference into the project.
In this example we will use jQuery CDN library.

Step 5: Create jQuery Ajax function to call controller JSON action method and invoke autocomplete function,
$(document).ready(function () {  
       $("#CityName").autocomplete({  
           source: function(request,response) {  
               $.ajax({  
                   url: "/Home/Index",  
                   type: "POST",  
                   dataType: "json",  
                   data: { Prefix: request.term },  
                   success: function (data) {  
                       response($.map(data, function (item) {  
                           return { label: item.Name, value: item.Name };  
                       }))  
  
                   }  
               })  
           },  
           messages: {  
               noResults: "", results: ""  
           }  
       });  
   })  
To work above function don't forget to add the reference of the following jQuery CDN library as,
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
<script src="//code.jquery.com/jquery-1.10.2.js"></script>  
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> 
Step 6:
Add view named index and put above json function into the view. After adding code necessary files and logic the Index.cshtml will look like the following,

Index.cshtml

@model AutoCompleteInMVCJson.Models.CityModel  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
<script src="//code.jquery.com/jquery-1.10.2.js"></script>  
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>  
<script type="text/javascript">  
    $(document).ready(function () {  
        $("#CityName").autocomplete({  
            source: function (request, response) {  
                $.ajax({  
                    url: "/Home/Index",  
                    type: "POST",  
                    dataType: "json",  
                    data: { Prefix: request.term },  
                    success: function (data) {  
                        response($.map(data, function (item) {  
                            return { label: item.Name, value: item.Name };  
                        }))  
  
                    }  
                })  
            },  
            messages: {  
                noResults: "", results: ""  
            }  
        });  
    })  
</script>  
@using (Html.BeginForm())  
{  
    @Html.AntiForgeryToken()  
  
    <div class="form-horizontal">  
  
        <hr />  
  
        <div class="form-group">  
  
            <div class="col-md-12">  
                @Html.EditorFor(model => model.CityName, new { htmlAttributes = new { @class = "form-control" } })  
  
            </div>  
        </div>  
  
    </div>  
}  
Now run the application and type any word then it will auto populate the records which exactly start with first word as in the following screenshot,
 
If you want to auto populate the records which contain any typed alphabet,then just change the LINQ query as contain. Now type any word it will search as follows,
 
From all the above examples, I hope you learned how to create the auto complete textbox using jQuery UI in ASP.NET MVC.

Note:
  • For the detailed code, please download the sample zip file.
  • Perform changes in Web.config file as per your server location.
  • You need to use the jQuery library.
Download Sample Code :  AutoCompleteInMVCJson.zip
    Summary

    For all the examples above, we learned how to use jQuery UI to create auto complete textbox in ASP.NET MVC. I hope this article is useful for all readers. If you have a suggestion then please contact me. 

    Disable jQuery Calendar Future and Past Date in MVC

    In any application validation is very important to avoid invalid data being inserted into the database which sometimes breaks the business process . Any booking system the date is very important, Consider an example, I have online ticket booking system such as BUS and what is happen if I allow past date and user booked the ticket of past date then what will be happen just Imagine .So by considering these type of business requirement I have decided to write this article which disable the past and future dates of calendar control as per our requirement.. So let us implement this requirement step by step,
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
    3. Choose MVC empty application option and click on OK
    Step 2: Add model class.
    Right click on Model folder in the created MVC application and add class named EmpModel and write the following line of code,
    EmpModel.cs
    public class EmpModel    
    {   
       [Display(Name ="Enter Date")]    
       public DateTime EnterDate { get; set; }    
    } 
    Step 3: Home controller

    Right click on Controller folder in the created MVC application and add the controller class,


    Now after selecting controller template, click on add button then the following window appears,



    Specify the controller name and click on Add button,

    HomeController.cs
    public class HomeController : Controller    
    {    
        // GET: Home    
        public ActionResult Index()    
        {    
            return View();    
        }    
    }   
    In the above code, The only action result method named Index handle the user request when the user request for the view named Index.cshtml which will be added later .

    Step 4: Reference jQuery UI.

    Reference jQuery UI css and js library reference as there are many ways to add the reference of jQuery library into our project. The following are some methods,
    • Using NuGet package manager, you can install library and reference into the project.
    • Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
    • Download jQuery files from jQuery official website and reference into the project.
    In this example we will use jQuery CDN library.

     As we know how to use jQuery UI calendar we need to use datepicker function and to set or allow specific date range in calendar we need to use the following properties of datepicker function,
    • yearRange: It sets the year range for calendar control such as how many past and future years to display in calendar.
    • minDate :  It sets the minimum date for calendar control .
    • maxDate : it sets the maximum date range for calendar control .
    Step 5: Create jQuery function to invoke datepicker function,
    $(document).ready(function() {  
        $("#EnterDate").datepicker({  
            dateFormat:"dd-mm-yy",  
            minDate: -0,  
            maxDate: "+0M +0D"  
      
        });  
    });
    For making the above function yo work don't forget to add the reference of the following jQuery CDN library as,
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">    
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>    
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>   
    Step 6: Add View.

    Add strongly typed view named index from EmpModel class as,



    After adding necessary code, files and logic the Index.cshtml code will look like the following,

    Index.cshtml
    @model DissablePastandFutureDateInMVC.Models.EmpModel  
      
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>  
      
    <script>  
      
      $(document).ready(function() {  
          $("#EnterDate").datepicker({  
              dateFormat:"dd-mm-yy",  
              minDate: -0,  
              maxDate: "+0M +0D"  
      
          });  
      });  
    </script>   
      
      
    @using (Html.BeginForm())   
    {  
        @Html.AntiForgeryToken()  
          
        <div class="form-horizontal">  
             
            <hr />  
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
            <div class="form-group">  
                @Html.LabelFor(model => model.EnterDate, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.EnterDate, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.EnterDate, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            
        </div>  
    }  
    Now run the application and put mouse pointer into the textbox the calendar control will popup as in the following screenshot,
     
    In the above screenshot you can see that only current date is enabled and all other dates are disabled. Now let us change the maxDate property to enable only five days from current date,
    $(document).ready(function() {  
        $("#EnterDate").datepicker({  
            dateFormat:"dd-mm-yy",  
            minDate: -0,  
            maxDate: "+0M +4D"  
      
        });  
    }); 
    Now run the application the output will be as follows:
     
    In the preceding screenshot you can see that only five dates are available including current date. From all the preceding examples, I hope you learned how to disable past and future dates using jQuery UI calendar control in ASP.NET MVC.

    Note:
    • For the detailed code, please download the sample zip file.
    • You need to use the jQuery library and if you are using CDN library then it requires active internet connection .
    Summary

    I hope this article is useful for all readers. If you have a suggestion then please contact me.

    Disable Past And Future Dates of jQuery UI Calendar

    Three years before I wrote the following article: Disable Future and past date in ASP.NET, which has huge response. Currently it has 68.2 k views. So by considering the same requirement in ASP.NET MVC I decided to write same type of article using ASP.NET MVC with the help of jQuery UI library. So let us implement this requirement step by step,
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
    3. Choose MVC empty application option and click on OK
    Step 2: Add model class.
    Right click on Model folder in the created MVC application and add class named EmpModel and write the following line of code,
    EmpModel.cs
    public class EmpModel    
    {   
       [Display(Name ="Enter Date")]    
       public DateTime EnterDate { get; set; }    
    } 
    Step 3: Home controller

    Right click on Controller folder in the created MVC application and add the controller class,


    Now after selecting controller template, click on add button then the following window appears,



    Specify the controller name and click on Add button,

    HomeController.cs
    public class HomeController : Controller    
    {    
        // GET: Home    
        public ActionResult Index()    
        {    
            return View();    
        }    
    }   
    In the above code, The only action result method named Index handle the user request when the user request for the view named Index.cshtml which will be added later .

    Step 4: Reference jQuery UI.

    Reference jQuery UI css and js library reference as there are many ways to add the reference of jQuery library into our project. The following are some methods,
    • Using NuGet package manager, you can install library and reference into the project.
    • Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
    • Download jQuery files from jQuery official website and reference into the project.
    In this example we will use jQuery CDN library.

     As we know how to use jQuery UI calendar we need to use datepicker function and to set or allow specific date range in calendar we need to use the following properties of datepicker function,
    • yearRange: It sets the year range for calendar control such as how many past and future years to display in calendar.
    • minDate :  It sets the minimum date for calendar control .
    • maxDate : it sets the maximum date range for calendar control .
    Step 5: Create jQuery function to invoke datepicker function,
    $(document).ready(function() {  
        $("#EnterDate").datepicker({  
            dateFormat:"dd-mm-yy",  
            minDate: -0,  
            maxDate: "+0M +0D"  
      
        });  
    });
    For making the above function yo work don't forget to add the reference of the following jQuery CDN library as,
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">    
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>    
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>   
    Step 6: Add View.

    Add strongly typed view named index from EmpModel class as,



    After adding necessary code, files and logic the Index.cshtml code will look like the following,

    Index.cshtml
    @model DissablePastandFutureDateInMVC.Models.EmpModel  
      
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>  
      
    <script>  
      
      $(document).ready(function() {  
          $("#EnterDate").datepicker({  
              dateFormat:"dd-mm-yy",  
              minDate: -0,  
              maxDate: "+0M +0D"  
      
          });  
      });  
    </script>   
      
      
    @using (Html.BeginForm())   
    {  
        @Html.AntiForgeryToken()  
          
        <div class="form-horizontal">  
             
            <hr />  
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
            <div class="form-group">  
                @Html.LabelFor(model => model.EnterDate, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.EnterDate, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.EnterDate, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            
        </div>  
    }  
    Now run the application and put mouse pointer into the textbox the calendar control will popup as in the following screenshot,
     
    In the above screenshot you can see that only current date is enabled and all other dates are disabled. Now let us change the maxDate property to enable only five days from current date,
    $(document).ready(function() {  
        $("#EnterDate").datepicker({  
            dateFormat:"dd-mm-yy",  
            minDate: -0,  
            maxDate: "+0M +4D"  
      
        });  
    }); 
    Now run the application the output will be as follows:
     
    In the preceding screenshot you can see that only five dates are available including current date. From all the preceding examples, I hope you learned how to disable past and future dates using jQuery UI calendar control in ASP.NET MVC.

    Note:
    • For the detailed code, please download the sample zip file.
    • You need to use the jQuery library and if you are using CDN library then it requires active internet connection .
    Summary

    I hope this article is useful for all readers. If you have a suggestion then please contact me.

    Disable Past And Future Dates of Calendar In ASP.NET MVC

    Three years ago, I wrote the following article:  Disable Future and Past Date in ASP.NET, which has had a huge response. It has currently received 68.2 million views. So, by considering the same requirement in ASP.NET MVC, I decided to write the same type of article using ASP.NET MVC with the help of the jQuery UI library. So let us implement this requirement step by step.
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
    3. Choose MVC empty application option and click on OK
    Step 2: Add model class.
    Right click on Model folder in the created MVC application and add class named EmpModel and write the following line of code,
    EmpModel.cs
    public class EmpModel    
    {   
       [Display(Name ="Enter Date")]    
       public DateTime EnterDate { get; set; }    
    } 
    Step 3: Home controller

    Right click on Controller folder in the created MVC application and add the controller class,




    Now after selecting controller template, click on add button then the following window appears,





    Specify the controller name and click on Add button,

    HomeController.cs
    public class HomeController : Controller    
    {    
        // GET: Home    
        public ActionResult Index()    
        {    
            return View();    
        }    
    }   
    In the above code, The only action result method named Index handle the user request when the user request for the view named Index.cshtml which will be added later .

    Step 4: Reference jQuery UI.

    As there are numerous ways to incorporate the jQuery library into our project, we will refer to the jQuery UI CSS and Js library reference. The following are some methods.
    • Using the NuGet package manager, you can install the library and reference it in the project.
    • Use the CDN library provided by Microsoft, jQuery, Google or any other which requires an active internet connection.
    • Download jQuery files from the official website and reference them in the project.
    In this example, we will use the jQuery CDN library.

    To learn how to use jQuery UI calendar, we must first understand the datepicker function. To set or allow a specific date range in the calendar, we must use the datepicker function's following properties: ,
    • yearRange: It sets the year range for calendar control such as how many past and future years to display in calendar.
    • minDate :  It sets the minimum date for calendar control .
    • maxDate : it sets the maximum date range for calendar control .
    Step 5: Create jQuery function to invoke datepicker function,
    $(document).ready(function() {  
        $("#EnterDate").datepicker({  
            dateFormat:"dd-mm-yy",  
            minDate: -0,  
            maxDate: "+0M +0D"  
      
        });  
    });
    For making the above function yo work don't forget to add the reference of the following jQuery CDN library as,
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">    
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>    
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>   
    Step 6: Add View.

    Add strongly typed view named index from EmpModel class as,




    After adding necessary code, files and logic the Index.cshtml code will look like the following,

    Index.cshtml
    @model DissablePastandFutureDateInMVC.Models.EmpModel  
      
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>  
      
    <script>  
      
      $(document).ready(function() {  
          $("#EnterDate").datepicker({  
              dateFormat:"dd-mm-yy",  
              minDate: -0,  
              maxDate: "+0M +0D"  
      
          });  
      });  
    </script>   
      
      
    @using (Html.BeginForm())   
    {  
        @Html.AntiForgeryToken()  
          
        <div class="form-horizontal">  
             
            <hr />  
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
            <div class="form-group">  
                @Html.LabelFor(model => model.EnterDate, htmlAttributes: new { @class = "control-label col-md-2" })  
                <div class="col-md-10">  
                    @Html.EditorFor(model => model.EnterDate, new { htmlAttributes = new { @class = "form-control" } })  
                    @Html.ValidationMessageFor(model => model.EnterDate, "", new { @class = "text-danger" })  
                </div>  
            </div>  
      
            
        </div>  
    }  


    Now run the application and put the mouse pointer into the textbox. The calendar control will popup as in the following screenshot.
     


     

    In the above screenshot, you can see that only the current date is enabled and all other dates are disabled. Now let us change the maxDate property to enable only five days from the current date.

    $(document).ready(function() {  
        $("#EnterDate").datepicker({  
            dateFormat:"dd-mm-yy",  
            minDate: -0,  
            maxDate: "+0M +4D"  
      
        });  
    }); 

    Now run the application the output will be as follows:





     


    In the preceding screenshot you can see that only five dates are available, including the current date. From all the preceding examples, I hope you learned how to disable past and future dates using the jQuery UI calendar control in ASP.NET MVC.

    Note:
    • You need to use the jQuery library, and if you are using the CDN library, then it requires an active internet connection.
    Summary
    I hope this article is useful for all readers. If you have a suggestion, then please contact me.

    www.CodeNirvana.in

    Protected by Copyscape
    Copyright © Compilemode