Search code examples
c#asp.net-mvcdatepickerrazorengine

Using datepicker to insert date into database


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.


Solution

  • 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