Friday, September 20, 2019

How to Add jQuery Datepicker in MVC

In this example we will describe how to add a jQuery Datepicker to a MVC application. jQuery is one of the widely used scripting languages for web development. jQuery provides built-in support for a DateTime picker. In this article I explain how to add a jQuery Datepicker with MVC.
The following is the procedure to add the jQuery Datepicker to a MVC application.
Step 1
Go to New project and select the Web tab and select ASP.Net Web Application. Provide a suitable name for your project, such as DateTimeDemo and click the OK button.
new web app

Step 2
Then following screen will appear. Select the MVC tab and click the OK button.
mvc template

Step 3
A project solution has been created with some pre-defend controllers, scripts and so on. Now go to the Model folder and a class called Employee with three auto-implemented properties like:
  1. public class Employee  
  2. {  
  3.     [Required]  
  4.     [Display(Name = "Id")]  
  5.     public int EmpId { get; set; }  
  6.     [Display(Name = "Name")]  
  7.     [Required]  
  8.     public string EmpName { get; set; }  
  9.     [Required]  
  10.     [Display(Name = "Date Of Birth")]  
  11.     [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]  
  12.     public DateTime DOB { get; set; }  
In this code I have done some basic Data annotation validation with all those three properties. You can ignore if you want.

Step 4
Now go to the Controllers folder and right-click on the Add Controller option then the following window will appear. Select MVC5 Controller-Empty. Provide a name for the controller, say Employee, and click on the Add button.
empty controller

Step 5
Controller code will be automatically generated with one Index action method like:
  1. public class EmployeeController : Controller  
  2. {  
  3.     // GET: Employee  
  4.     public ActionResult Index()  
  5.     {  
  6.         return View();  
  7.     }  
Step 6
Right-click anywhere on the Index action method and click add view then select the Employee model class and add that view of type Create as in the following:
add view

Step 7
Then the Employee create view will be automatically generated with the following code.
  1. @model DateTimeDemo.Models.Employee  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9.   
  10. @using (Html.BeginForm())   
  11. {  
  12.     @Html.AntiForgeryToken()  
  13.       
  14.     <div class="form-horizontal">  
  15.         <h4>Employee</h4>  
  16.         <hr />  
  17.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  18.         <div class="form-group">  
  19.             @Html.LabelFor(model => model.EmpId, htmlAttributes: new { @class = "control-label col-md-2" })  
  20.             <div class="col-md-10">  
  21.                 @Html.EditorFor(model => model.EmpId, new { htmlAttributes = new { @class = "form-control" } })  
  22.                 @Html.ValidationMessageFor(model => model.EmpId, ""new { @class = "text-danger" })  
  23.             </div>  
  24.         </div>  
  25.   
  26.         <div class="form-group">  
  27.             @Html.LabelFor(model => model.EmpName, htmlAttributes: new { @class = "control-label col-md-2" })  
  28.             <div class="col-md-10">  
  29.                 @Html.EditorFor(model => model.EmpName, new { htmlAttributes = new { @class = "form-control" } })  
  30.                 @Html.ValidationMessageFor(model => model.EmpName, ""new { @class = "text-danger" })  
  31.             </div>  
  32.         </div>  
  33.   
  34.         <div class="form-group">  
  35.             @Html.LabelFor(model => model.DOB, htmlAttributes: new { @class = "control-label col-md-2" })  
  36.             <div class="col-md-10">  
  37.                 @Html.EditorFor(model => model.DOB, new { htmlAttributes = new { @class = "form-control", placeholder = "Employee Date Of Birth", @readonly = "true" } })  
  38.                 @Html.ValidationMessageFor(model => model.DOB, ""new { @class = "text-danger" })  
  39.             </div>  
  40.         </div>  
  41.   
  42.         <div class="form-group">  
  43.             <div class="col-md-offset-2 col-md-10">  
  44.                 <input type="submit" value="Create" class="btn btn-default" />  
  45.             </div>  
  46.         </div>  
  47.     </div>  
  48. }  
  49.   
  50. <div>  
  51.     @Html.ActionLink("Back to List""Index")  
  52. </div>  
  53.   
  54. @section Scripts {  
I have made some basic changes with the HTML of the DOB properties of this model, you may ignore it if you want.
Step 8
Now we need to add the reference of jQueryUi to the project. By default Visual Studio will not add a reference of jQueryUI for us. So to add the jQueryUi reference right-click on the References tab then select Manage NuGet Packages as in the following:
manage nuget package

Step 9
Now search for jQueryUI and select Install to install it.
install jquery

If your project already has the reference of jQueryUI then it will show as in the following tik mark.
 jquery installed

Step 10
Once the references for jQueryUI have been added to your project you can check your Content and scripts folder and it will have the files showing in the following images:
solution explorer
 jquery

Step 11
Now simply go to the App_Start folder and open BundleConfig.cs. There will be some default code there. Leave the code and add the following code:
  1. //Create bundel for jQueryUI  
  2. //js  
  3. bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(  
  4.           "~/Scripts/jquery-ui-{version}.js"));  
  5. //css  
  6. bundles.Add(new StyleBundle("~/Content/cssjqryUi").Include(  
  7.        "~/Content/jquery-ui.css")); 
The preceding code will create a bundle for jQueryUI scripts and CSS. Now you just need to add those bundles to the page where you want the DatePicker.
Step 12
Now go to the index view and add the following code to the Scripts section of the view.
  1. @section Scripts {  
  2.   
  3. @Scripts.Render("~/bundles/jqueryui")  
  4. @Styles.Render("~/Content/cssjqryUi")  
  5.   
  6.  <script type="text/javascript">  
  7.      $(document).ready(function () {  
  8.          $('input[type=datetime]').datepicker({  
  9.              dateFormat: "dd/M/yy",  
  10.              changeMonth: true,  
  11.              changeYear: true,  
  12.              yearRange: "-60:+0"  
  13.          });  
  14.   
  15.      });  
  16. </script>  
  17.   
Step 13
That's it. Run the Index view and you will get the date picker as in the following:
run

Notice the code inside scraps I have used following code there:
  1. dateFormat: "dd/M/yy",  
  2. changeMonth: true,  
  3. changeYear: true,  
  4. yearRange: "-60:+0" 
These are the customizations of jQueryUI that provide customization of the DatePicker depending on the needs of the developer. For all the default customizations go through jQuery Documentation.

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...