In this article I will explain you, how to use jquery calendar control in ASP.NET MVC. Here I will also describe that how to pass selected date of calendar to controller.
Create a property in a model class that returns a date to a caller. In the below class I had created a property named Date in which we can set Date value or we can get Date from that property.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace MVCCalendar.Models
{
public class ModelClass
{
[Required(ErrorMessage = "Date Required")]
public string Date
{
get;
set;
}
}
}
We have to add following jquery file (jquery-1.6.2.min.js, jquery-ui-1.8.16.custom.min.js) to use the calendar control in View. I have also created a javascript function in script tag that call’s the datepicker function.
When you click on submit button it will call another view (SubmitDate) that return a selected date.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MVCCalendar.Models.ModelClass>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#datepicker").datepicker();
});
</script>
</head>
<body>
<% using (Html.BeginForm("SubmitDate", "Home", FormMethod.Post))
{%>
<div>
<div class="demo">
<p>
Date:
<%: Html.TextBoxFor(x => x.Date, new { id = "datepicker" })%>
<input type="submit" value="Submit" />
</p>
</div>
<%} %>
</div>
</body>
</html>
In a Controller class, Index action returns a view and SubmitDate action returns a date if you selected, else it will give a message "You have not selected any date".
using System.Web.Mvc;
using MVCCalendar.Models;
namespace MVCCalendar.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public string SubmitDate(ModelClass model)
{
if (ModelState.IsValid)
{
return "You have selected a date : <b>" + model.Date.ToString() + "</b>";
}
return "You have not selected any date";
}
}
}
After completing the above process you can see an output of your project by pressing F5. In the browser it will show you a textbox and when you set a focus on textbox it will show you a calendar. You can select a date from calendar.
When you select a country and click on submit button, it will call Submit action from the Controller and show you a selected date.
By using above process you can simply learn that how to use calendar and get a selected value from the calendar in MVC.
Leave Comment