Jquery DatePicker in
MVC4 (Displaying the calendar and capturing the selected value to save it)
Requirement:
Show the date on in a view and this display should allow
user to set a new date using a calendar. The calendar should show on the click
of the textbox where the date is displayed.
Solution:
For the view
In the _Layout.cshtml(which resides in the Shared folder
under Views) ,define
@RenderSection("scripts", required: false)
In the view where the datepicker is defined, use the
follwing jQuery code
@section scripts{
<script type="text/javascript">
$(function
() {
$("#txtNewDate").datepicker({
onSelect: function
(date) { $("#_newDate").val(date) }
});
});
</script>
To format the styling (size, font etc) of the ui-datepicker,
include the following code:
<style type="text/css">
.ui-datepicker {
font-family:Garamond;
font-size: 12px;
margin-left:10px
}
</style>
In
the form tag, define a hidden field to capture the new date, also get the
current date value from the database
@using
(@Html.BeginForm())
{
<input type="hidden" id="_newDate" name="_ newDate "/>
<div>
<div>Date:</div><div ><input style="width:5em;height:2em; " type="text" id=" txtNewDate " value="@Html.Raw(Model.NextCall)"/></div>
</div>
<div>
<div><input type="submit"
style="height:2em" value="save"
name="save"
title="Save"
id="btnSave"
/></div>
</div>
}
For the Controller:
In the POST action method , use formCollection
[HttpPost]
[ActionName("details")]
public ActionResult details_Post(int
id, FormCollection form)
{
//define
a datetime variable
DateTime Nxtdate = DateTime.MinValue;
if (form["_newDate "] !=
"")
{
//convert the form variable
containing date to datetime type
Nxtdate = Convert.ToDateTime(form["_newDate "]);
}
if (ModelState.IsValid)
{
//call method to update the
date
Repository.SaveDate(Nxtdate);
}
Return
view();
}
For the
Repository(Model):
Saving the NewDate
public static void SaveDate(DateTime NxtCall, int Id)
{
try
{
//open
the connection
using
(SWSData db = new
ef.SWSData())
{
//get the row to be updated
var dbDate = db.Date.SingleOrDefault(ld => ld.id == Id);
if ( dbDate != null)
{
if (NxtCall != DateTime.MinValue)
{
dbDate.CallDate
= NxtCall;
}
}
//if the data does not exist already, insert a new record for the same.
else
{
Date
ld = new Date()
{
CallDate =
NxtCall,
};
db.AddToDate(ld);
}
//save changes to database
db.SaveChanges();
}
}
catch
(Exception ex)
{
if
(HttpContext.Current.IsDebuggingEnabled)
{
throw
ex;
}
}
}

No comments:
Post a Comment