Search code examples
jqueryasp.net-mvcrazoreonasdan-datetimepicker

Setting Min-Date for DateTime picker


I am using the Bootstrap 3 Datepicker, specifically the No Icon (input field only) version.

I am trying to use the minDate function so that the user will not be able to enter a date that is before the date that I choose, but I am unable to figure out how to set this up with the no icon version. I can do this with the icon.

Here is what I have:

HTML/Razor


@{
    var firstDate = new Test.Models.MS();
    using (var db = new UCEntities())
    {
        firstDate = db.MSies.Where(x => x.AID == Model.AId && x.deleted == false).OrderBy(x => x.Date).FirstOrDefault();
    }
}

<div class="col-md-4">
    <div class="input-group date date-search-box" data-mindate="@firstDate.Date">
        @Html.TextBox("date", null, htmlAttributes: new { id = "datetimepicker1", @class = "form-control", @placeholder = "Enter Date"})
        <span class="input-group-btn">
            <button class="btn btn-primary" type="submit">Search Date</button>
        </span>
    </div>
</div>

jQuery


$(document).ready(function () {
    $("#datetimepicker1").datetimepicker({
        format: 'MM/DD/YYYY',
        minDate: $("#datetimepicker1").data("mindate")
    });
});

I feel like the data-mindate needs to be included in the @Html.TextBox overload helper method, but how?

Also I know that doing logic in the view is frowned upon and that I could/should use a View Model, but I just want to test this out first.

Any help is appreciated.


Solution

  • Ahh I figured this out. With adding data attributes to razor Html helpers you have to use _ instead of a -.

    For example:

    @Html.TextBox("date", null, htmlAttributes: new { id = "datetimepicker1", @class = "form-control", @placeholder = "Enter Date",data_mindate=firstDate.Date})
    

    Instead of:

    @Html.TextBox("date", null, htmlAttributes: new { id = "datetimepicker1", @class = "form-control", @placeholder = "Enter Date",data-mindate=firstDate.Date})