Tuesday, July 30, 2013

Calender Control in MVC3 with Examples

Now for this article first create a an mvc3 article.  In this add the model and add the below code in it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class UserDate
    {
        public string SelectedDateFromCander { get; set; }
    }
}

Now create controller and add the below code.
   [HttpGet]
        public ActionResult Index()
        {
            UserDate _objmodel = new UserDate();
            return View(_objmodel);
        }

Now create view and add the below code.
@model MvcApplication1.Models.UserDate
@{
    ViewBag.Title = "jQuery UI Datepicker Restrict date range In MVC3 TextBoxFor Control | Code To Allow User Select Previous Date in MVC3";
}
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
    $(function () {
        $("#txtdatepicker").datepicker({ maxDate: "+0D" });
    });
</script>
@using (Html.BeginForm("index", "Home"))
{
    <h3>
        Select Date Before Current Date</h3>
    <p>
        Select Date: @Html.TextBoxFor(m => m.SelectedDateFromCander, new { id = "txtdatepicker" })</p>
    <input type="submit" value="Submit" />
    <br />
    <h3>Your Selected Date : @ViewBag.SelectedDate </h3>
}

Now add the below modified code in your controller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        [HttpGet]
        public ActionResult Index()
        {
            UserDate _objmodel = new UserDate();
            return View(_objmodel);
        }
        [HttpPost]
        public ActionResult Index(UserDate _objmodel)
        {
            ViewBag.SelectedDate = _objmodel.SelectedDateFromCander;
            return View(_objmodel);
        }
    }
}

In above code we have written code for post method also. Now we have done run the aplication.

datetime

Now we will check the system date.

datetime

Now click on text box to view the calender. in this user will now able to select beyond current date.

datetime

Now select the date and click on submit to get the selected date in controller.
datetime

Now in controller you will the selected date as shown below.

datetime

Now here is the final output.

datetime

The above date in mm/dd/YYYYY format....

No comments:

Post a Comment