Disabled Dates from Table in DB

2 posts, 0 answers
  1. Tyler
    Tyler avatar
    9 posts
    Member since:
    May 2018

    Posted 15 Aug Link to this post

    I'm working in MVC 5 and am using Entity Framework.

    I want to be able to disable dates in a datepicker where the disabled dates are pulled from a table in the DB, for example the Holidays table where the dates are in a columns called HOLIDAYDATE. I see how to hard code the dates but how do you pull the dates from a data source and load them into the datepicker?

     

  2. Georgi
    Admin
    Georgi avatar
    368 posts

    Posted 17 Aug Link to this post

    Hello Tyler,

    A possible solution is to pass the array of the dates that should be disabled to the view and using the approach from the following demo disable the dates in the DatePicker:


    e.g.

    // add a collection property to the view model which will store the disabled dates
     
        public class ViewModel
        {
            public ICollection< DateTime> DisabledDates { get; set; }
        }
     
    // in the action fetch the dates from the db and pass them to the view
     
            public ActionResult Index()
            {           
                var disabledDates = service.GetDisabledDates();
     
                return View(new DatesModel { DisabledDates = disabledDates});
            }
     
    // in the view add a picker with a disabled dates handler
     
    @model ViewModel
    @{
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    }
     
    @(Html.Kendo().DatePicker().Name("picker").DisableDates("disableDates"))
     
    <script>
        function disableDates(date) {
            var dates = "@string.Join(",", Model.DisabledDates)".split(',').map(x => new Date(x));
            if (date && compareDates(date, dates)) {
                return true;
            } else {
                return false;
            }
        }
     
     
        function compareDates(date, dates) {
            for (var i = 0; i < dates.length; i++) {
                if (dates[i].getDate() == date.getDate() &&
                    dates[i].getMonth() == date.getMonth() &&
                    dates[i].getYear() == date.getYear()) {
                    return true
                }
            }
        }
    </script>

    For your convenience I am attaching a small sample which demonstrates the above approach.


    Regards,
    Georgi
    Progress Telerik
    Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Back to Top