JQuery Calendar In ASP.NET MVC

Here we will learn how to use JQuery in ASP.NET MVC and we will create a DateTime picker using JQuery.

Open Visual Studio and create a new project and select a MVC 4 application then you select an “Internet Application" and click OK.

MVC4

If you want to use Empty instead of internet application then you need to add some jQuery script and CSS these jQuery scripts are available when we createa  project using internet application.

You can copy this Content and script folder from this internet application and put it in empty template project.

template
Step 1 - Go to Sql Server management system and execute following script.

  1. Create database MVCVariousAttribute  
  2. use MVCVariousAttribute  
  3. Create table Student  
  4. (  
  5. Id int primary key identity,  
  6. FullName nvarchar(100),  
  7. Gender nvarchar(10),  
  8. Age int,  
  9. AdmissionDate DateTime,  
  10. EmailAddress nvarchar(100),  
  11. WinningPrize int,  
  12. PersonalWebSite nvarchar(100)  
  13. )  
  14. Insert into Student values  
  15. ('Munesh Sharma''Male', 25, '2005-05-05 16:53:36.975''[email protected]', 45000,'http://dotnet-munesh.blogspot.in/')  
  16. Insert into Student values  
  17. ('Rahul Sharma'NULL, 30, '2006-06-06 17:42:25.865''[email protected]', 35000,'http://dotnet-munesh.blogspot.in/')  
Step 2

Go to Visual studio and add a new project, select “ASP.NET MVC4 Web Application” and give the name for this. In my case it is “JqueryCalendar” -> Select a Project template as Empty and View engine is “Razor”, Then Click OK.

Step 3

Add “EntityFramework dll” to reference folder in your project. If you don’t have then install it through nugget package manager for more go this Go here.

Step 4

Right click on Model folder and add “ADO.NET Entity Data Model” and give the name it as “StudentDataModel”, Then click on Add.

Step 5

When You will click Add button here you will see another window for “EntityData modal Wizard” from there you select “Generate From DataBase”, And Click Next.

Give the connection name and select your database then click on next.

next

Step 6 - In this screen select your Database Tables and give Modal Name then click FINISH Button.

FINISH

FINISH

When you will click on finish button it will create Student Entity.

Student

Step 7

Now at this position go to controller folder -> right click on this folder and add a controller with the name “CalendarController”, It will create a Calendar controller , write the following code on this page.

controller
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using JqueryCalendar.Models;  
  7. namespace JqueryCalendar.Controllers   
  8. {  
  9.     public class HomeController: Controller   
  10.     {  
  11.         public ActionResult Details(int id)  
  12.         {  
  13.                 MVCVariousAttributeEntities _context = new MVCVariousAttributeEntities();  
  14.                 Student _studentDetail = _context.Students.Where(c => c.Id == id).SingleOrDefault();  
  15.                 return View(_studentDetail);  
  16.             }  
  17.             //  
  18.             // GET: /Home/Create  
  19.         public ActionResult Create()  
  20.         {  
  21.                 return View();  
  22.             }  
  23.             //  
  24.             // POST: /Home/Create  
  25.             [HttpPost]  
  26.         public ActionResult Create(FormCollection collection)  
  27.         {  
  28.                 try   
  29.                 {  
  30.                     // TODO: Add insert logic here  
  31.                     return RedirectToAction("Index");  
  32.                 } catch  
  33.                 {  
  34.                     return View();  
  35.                 }  
  36.             }  
  37.             //  
  38.             // GET: /Home/Edit/5  
  39.         public ActionResult Edit(int id)   
  40.         {  
  41.                 return View();  
  42.             }  
  43.             //  
  44.             // POST: /Home/Edit/5  
  45.             [HttpPost]  
  46.         public ActionResult Edit(int id, FormCollection collection)   
  47.         {  
  48.                 try   
  49.                 {  
  50.                     // TODO: Add update logic here  
  51.                     return RedirectToAction("Index");  
  52.                 } catch   
  53.                 {  
  54.                     return View();  
  55.                 }  
  56.             }  
  57.             //  
  58.             // GET: /Home/Delete/5  
  59.         public ActionResult Delete(int id)   
  60.         {  
  61.                 return View();  
  62.             }  
  63.             //  
  64.             // POST: /Home/Delete/5  
  65.             [HttpPost]  
  66.         public ActionResult Delete(int id, FormCollection collection)   
  67.         {  
  68.             try   
  69.             {  
  70.                 // TODO: Add delete logic here  
  71.                 return RedirectToAction("Index");  
  72.             } catch   
  73.             {  
  74.                 return View();  
  75.             }  
  76.         }  
  77.     }  
  78. }  
Step 8

Next step is to add a view for detail action method so right click on this method -> add view -> Scaffold template as Detail.

add

It will generate a code for Detail view, now run your application and redirect to the following URL,

http://localhost/JqueryCalendar/Calendar/Details/1

It is with home controller then detail action method with ID “1”, When we see this output, we see that it is not good which means there is no gap in FullNamefor other things so for that we will use attribute.

Step 9

When we create a application using entityFramework we add a EntityDataModel then we give connection and select tables that time it creates a class in model (Designer class). Partial for this modal.edmx (student.cs class) for making some changes like design is not looking good and for date there is no calander.

This auto generated class(modal1.edmx) is a partial class so we can create a another student partial class and we can make changes there.

So in modal folder add a class and give the name as “Student.cs” and write the following code in this class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ComponentModel.DataAnnotations;  
  6. using System.ComponentModel;  
  7. namespace JqueryCalendar.Models   
  8. {  
  9.     [MetadataType(typeof(StudentMetaData))]  
  10.     public partial class Student {}  
  11.     public class StudentMetaData  
  12.     {  
  13.         //If you want "FullName" to be displayed as "Full Name",  
  14.         //use DisplayAttribute or DisplayName attribute.  
  15.         //[DisplayAttribute(Name="Full Name")]  
  16.         //[Display(Name = "Full Name")]  
  17.         [DisplayName("Full Name")]  
  18.         public string FullName  
  19.         {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public DateTime ? AdmissionDate   
  24.         {  
  25.                 get;  
  26.                 set;  
  27.             }  
  28.             // If gender is NULL, "Gender not specified" text will be displayed.  
  29.             [DisplayFormat(NullDisplayText = "Gender not specified")]  
  30.         public string Gender   
  31.         {  
  32.             get;  
  33.             set;  
  34.         }  
  35.         //If you don't want to display a column use ScaffoldColumn attribute.  
  36.         //This only works when you use @Html.DisplayForModel() helper  
  37.         [ScaffoldColumn(false)]  
  38.         public int ? WinningPrize   
  39.         {  
  40.             get;  
  41.             set;  
  42.         }  
  43.     }  
  44. }  
At this point Run your application and go to the following URl and the output will be,

http://localhost:43552/Calendar/Edit/1

save

Here you will see that Admission Date text box has the date and here the user has to put date manually which is not a good practice there should be a calendar so that the user can enter any date according to particular format.

The following is the convention used by MVC to find the customized templates,
  1. The customized display templates must be in a sub-folder that is named -DisplayTemplates. Editor templates must be in a sub-folder that is named -EditorTemplates.

  2. These sub-folders can live in "Shared" folder, or a specific views folder. If these folders are present in the Shared folder, then the templates are available for all the views. If they are in a specific views folder, then, they are available only for that set of views.

  3. The name of the template must match the name of the type. For example, as we are customizing DateTime template, the name of the template in this case has to be DateTime.ascx or DateTime.cshtml.

Adding a Custom DateTime Editor template

Step 1


If "Shared" folder does not already exist in your project(In View Folder), right click on the project in solution explorer and add it. In shared folder file is available to entire project for all the view.

Step 2 - Right click on the "Shared" folder, and add a "EditorTemplates" folder.

Step 3 - Right click on "EditorTemplates" folder and add a view with name = DateTime this view name should match with the property type here with have property type name is DateTime.

Step 4 - Copy and paste the following code in DateTime.cshtml partial view@model DateTime?

@Html.TextBox("", (Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") :string.Empty), new { @class = "date" })

Note - Please refer to the following MSDN articel for all the DateTime format strings.

Step 5 - Copy and paste the following code in Edit.cshtml view,

  1. @model MVCDemo.Models.Employee  
  2. @{  
  3. ViewBag.Title = "Edit";  
  4. }  
  5.   
  6.   
  7. <h2>Edit</h2>  
  8. <script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>  
  9. <script src="~/Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>  
  10. <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />  
  11. <link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />  
  12. <script type="text/javascript">  
  13. $(function()   
  14. {  
  15. $("input:text.date").datepicker(  
  16. {  
  17. dateFormat: "dd/mm/yy"  
  18. });  
  19. });  
  20. </script>  
  21.   
  22. @using (@Html.BeginForm())  
  23. {   
  24. @Html.EditorForModel()  
  25.   
  26. <br />  
  27. <input type="submit" value="Save" />  
  28. }  
Note - Please refer to the following jQuery link for DateTime format strings,

The following jQuery scripts and css files are required for jQuery DateTime picker control. However, these files may change depending on the version of jQuery you are working with.

Scripts/jquery-1.7.1.min.js
Scripts/jquery-ui-1.8.20.min.js
Content/Site.css
Content/themes/base/jquery.ui.all.css


Now run your application you will see that datepicker at admission Date text box you can go to my blog also.


Similar Articles