Using datepicker to insert date into database

1.9k Views Asked by At

I'm new to asp.net MVC 5. There is a column in my database which has the type of DateTime, and I want to use datepicker to insert date into it. However, it gave me an error. the error

my model is like

[Display(Name = "Found Date")] public System.DateTime foundDate { get; set; }

my view is

    <div class="form-group">
        @Html.LabelFor(model => model.foundDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.foundDate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.foundDate, "", new { @class = "text-danger" })
        </div>
    </div>

script

$(document).ready(function () { $("#foundDate").datepicker( {dateformat: 'dd/MM/yyyy'} ); });

Which date format should be passed to the datetime in the database? How can I change it so that it matches the datepicker's return type?

Any help to solve this problem would be appreciated.

3

There are 3 best solutions below

1
On BEST ANSWER

You can try specifying the datetime format using DataAnnotaions

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]

And you can also use conventional HTML5 date time control, just specify the DataType of you model property with the help of data annotation instead of jquery datetime picker like

[DataType(DataType.DateTime)]

hopefully it will help helps

0
On

You configured it

$("#foundDate").datepicker( {dateformat: 'dd/MM/yyyy'} );

but the input is in MM/dd/yyyy.

0
On

First download the globalize.js , globalize.culture.en-GB.js files and link the these files into your Html page.Finally paste the following code into your script tag.

<script src="~/Scripts/globalize.js"></script>
<script src="~/Scripts/globalize.culture.en-GB.js"></script>
$(document).ready(function () {
    $.culture = Globalize.culture("en-GB");
    $.validator.methods.date = function (value, element) {
        return this.optional(element)
            || Globalize.parseDate(value, "dd/MM/yyyy", "en-GB")
            || Globalize.parseDate(value, "yyyy-mm-dd");
    }
$("#foundDate").datepicker( {dateformat: 'dd/MM/yyyy'} );
});