Wednesday, February 6, 2019

MVC datepicker editor template

To add datepicker template by default to all datetime fields follow the steps mentioned below:


1) Make sure jquery, jquery-ui, jquery-validate and jquery-validate-date libaries are being used
2) Add datetime editor template at View/Shared/EditorTemplates/DateTime.cshtml
@model DateTime?
@{
    var value = "";
    if (Model.HasValue)
    {
        value = String.Format("{0:d}", Model.Value.ToString("dd/MM/yyyy"));
    }
}

@Html.TextBox("", value, new { @class = "datepicker", type = "text" })

2) Add DataType and DisplayFormat attributes to all datetime fields
        [DataType(DataType.DateTime)]

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

3) Add globalization tag to web.config
   <system.web>
    <globalization culture="en-GB" uiCulture="en-GB" enableClientBasedCulture="false"></globalization>
  </system.web>

4) Add date validation and datepicker bind script to document on load

jQuery(document).ready(function ($) {
    $.validator.addMethod('date', function (value, element) {
        if (this.optional(element)) {
            return true;
        }
        var valid = true;
        try {
            $.datepicker.parseDate('dd/MM/yyyy', value);
        }
        catch (err) {
            valid = false;
        }
        return valid;
    });
    $('.datepicker').datepicker({ dateFormat: 'dd/MM/yyyy' });

});

5)

No comments:

SSL Error - The connection for this site is not secure

 After cloning a git repo of dot net framework website and trying to run it all I could see was this error Turns out the fix was to simply e...