Search code examples
c#asp.net-corerazordatepickerasp.net-core-mvc

Set date from model for Datepicker in ASP.NET Core MVC


I have a bootstrap datepicker in my ASP.NET Core MVC application. This works so far. Now I want the start date (for example 20.06.2023) to be taken from my model and displayed and highlighted in the date picker. The date in the past should not be selectable, greyed out.

This is my current datepicker.

<script type="text/javascript">
    $(document).ready(function () {
        $("#datepicker").datepicker({
            startDate: new Date(),
            language: "de"
        });
    });
</script>

Here I have tried to take the date from the model, but it does not work.

<script type="text/javascript">
$(document).ready(function(){
    var dateStart= new Date('@Model.DateStart');

    $("#datepicker").datepicker({    
        startDate: dateStart,        
        language: "de"
    });
});
</script>

This is how I implement the datepicker

<div class="form-group row">                            
                        <div class="col-sm-3" >                                                                                         
                            <input type="text" asp-for="DateStart" class="form-control" id="datepicker"/>                            
                            @Html.ValidationMessageFor(model => model.DateStart, "", new { @class = "text-danger" })
                        </div>
                    </div>

And this is the property

public string? DateStart{ get; set; }

What else do I have to adjust to make it work? Thank you.


Solution

  • I have found a solution:

    <script type="text/javascript">
    $(document).ready(function () {
        var dateStart = "@Model.DateStart";
        var arrayStr = dateStart.split(".");        
        var dateStartNew = new Date(arrayStr[2], arrayStr[1] - 1, arrayStr[0]);         
    
        if (dateStartNew < Date.now()) {
            dateStartNew = new Date();
        }
    
        dateStartNew.setDate(dateStartNew.getDate() + 1);
    
        $("#datepicker").datepicker({
            startDate: dateStartNew,
            language: "de",
            beforeShowDay: function (date) {
                var startDate = new Date(dateStartNew.getFullYear(), dateStartNew.getMonth(), dateStartNew.getDate());
    
                if (date.getTime() === dateStartNew.getTime()) {
                    return {
                        classes: 'highlighted',
                        tooltip: 'Start Date'
                    };
                }
            }
        });
    });
    

    Thank you.