//method in controller to return list of dates.
public ActionResult GetDisabledDates(string id)
{
//get list of dates separated by comma
...
return Json(new {disabledDatesArray = result }, JsonRequestBehavior.AllowGet);
}
$(document).ready(function () {
//Call GetDisabledDates in the controller, passing id
$.getJSON("GetDisabledDates", {
id: "identifier"
},
function(data) {
//write date values to hidden field for retrieval later.
//and to ensure we only have to call server side method once.
$('#hiddenDates').val(data.disabledDatesArray);
});
function IsDateAvailable(date) {
//we have to pad the date, to ensure we can compare with the dates we retrieve from serverside.
var dmy = padDate(date.getDate()) + "/" + padDate(date.getMonth()+1) + "/" + date.getFullYear();
//remove dates in array from datepicker.
if (IsDateInUnavailableList(dmy)) {
//date exists in list of those not allowed.
return [false,"","Unavailable"];
} else {
return [true,"","Available"];
}
}
//pad out dates to allow comparison, 1/1/2012 will become 01/01/2012
function padDate(i) {
return (i < 10) ? "0" + i : "" + i;
}
//define datepicker
$("#datepicker").datepicker({ dateFormat: 'dd/mm/yy', minDate: 0, beforeShowDay: IsDateAvailable });
EnableOrDisableSaveButton();
$("#datepicker").change(function () {
EnableOrDisableSaveButton();
});
function IsDateInUnavailableList(date)
{
var dateValues = $("#hiddenDates").val();
//convert back into an array.
var dateArray = dateValues.split(",");
//check date against dates in array
if ($.inArray(date, dateArray) < 0) {
return false;
}
else {
return true;
}
}
// Function to enable or Disable the Save Button
function EnableOrDisableSaveButton() {
var date = $('#datepicker').val();
// Now enable the button if the above two values or not empty
if (date != "") {
//prevent save button click if date selected in list of disallowed dates.
if (IsDateInUnavailableList(date)) {
$("#Save").attr("disabled", true);
}
else {
$("#Save").attr("disabled", false);
}
}
else {
$("#Save").attr("disabled", true);
}
}
//hidden field to store date values.
<input id="hiddenDates" name="hiddenDates" style="display: none;" />
//datepicker
@Html.TextBoxFor(m => m.Date, new { id = "datepicker", @maxlength = 10, style = "width:65px" })
<input id="Save" title="Click here to save" type="submit" value="Save" />
No comments:
Post a Comment