简体   繁体   中英

set default date using datepicker in jQuery and Razor (c#)

We have a common.js file which contains the commonly used client/jquery related functions and validations. This common.js is included in the _Layout.cshtml. In this common.js file we have datepicker code, to maintain uniformity across application, as below,

function OsDatepicker(id, date, maxdt, dDate) {
    var ctrl = "#" + id;
    var d = new Date();

    var currYear = d.getFullYear();
    if (date == 0)
        var yrrange = (parseInt(currYear) - 4) + ":" + (parseInt(currYear) + 2);
    else
        var yrrange = (parseInt(currYear) - 70) + ":" + (currYear);

    $(ctrl).datepicker({ dateFormat: 'dd/mm/yy',
        changeYear: true,
        autoSize: true,
        yearRange: yrrange,
        constrainInput: true,
        showOn: "both",
        buttonImage: '../../../Content/images/Calendar.png',
        buttonImageOnly: true,
        showanim: "slide",
        //defaultDate: dDate,  //not working  
        inline: true
    });

    if (maxdt == 0)
        $(ctrl).datepicker("option", "maxDate", "+0d");

    $(ctrl).datepicker("option","setDate", new Date(dDate)); //not working
}

The above function is called in the cshtml script as below,

$(document).ready(function () {
var dobDate = $("#Date_Of_Birth").val();
var jtDate = dobDate.split(" ");
OsDatepicker('Date_Of_Birth', 1, 0, jtDate[0]);
});

My razor code is as below, for Date of Birth

<div style="width: 260px; float: left; height: 45px;">
    <label class="field_title">
        @Html.LabelFor(model => model.Date_Of_Birth)</label>
    <div class="form_input">
        @Html.EditorFor(model => model.Date_Of_Birth)
        @Html.ValidationMessageFor(model => model.Date_Of_Birth)
    </div>
</div>

The markup of the above is as below,

<input class="text-box single-line" id="Date_Of_Birth" name="Date_Of_Birth" type="text" value="13-10-1988 00:00:00" />

As you can see the model is fetching the date correctly, which also being passed to the OSDatepicker function correctly.

On loading the form the DateofBirth textbox is blank, unable to crack this. Your suggestions would be helpful. Thanks in advance.

I think this is because the dateFormat that razor is rendering does not match the format the date picker is expecting.

Have you tried changing dateFormat: 'dd/mm/yy' to dateFormat: 'dd-mm-yyyy' ?

尝试这个:

defaultDate: $("#Date_Of_Birth").val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM