ASP.NET MVC 4 does not work with jquery datepicker

11,598

Solution 1

You need to tell the DatePicker that you aren't using a month first date format:

$.datepicker.setDefaults({
    dateFormat: "dd/mm/yy"
});

However, that is probably not a big part of your problem (and depending upon your browser culture, it is likely that the date picker was already using a day first date format).

There are also issues with day first date formats and the jQuery validation, as well as the MVC binding. This is one of the main reasons I stick with a year first date format (yyyy-mm-dd), since it is parsed correctly by all the various libraries.

Solution 2

JQuery is an option but you could take a .NET approach. I assume StartDate and EndDate are coming from a ViewModel and are of DateTime type ?

Simply use@Html.EditorFor intead of @Html.TextBoxFor and right away your controls will be turned into DatePickers.

You can also set specific rules on how your Dates will display and behave by specifying data annotation attributes on your ViewModel DateTime. For example this could be your StartDate Viewmodel property:

[DisplayFormat(NullDisplayText = "", DataFormatString = "{0:d}")]
[Display(Name = "Start Date")]
public DateTime? StartDate{ get; set; }

Not sure how to format your datepicker with C# further ? No problem, continue with JQuery:

$(':input[data-datepicker]').datepicker({ dateFormat: 'dd/mm/yy' });
Share:
11,598
antedesk
Author by

antedesk

I'm a Computer Engineer and a Dr in Applied Electronic. I attended Roma Tre University where I completed my PhD at the Engineering Department. During my PhD, I worked for the Signal Processing for Telecommunications and Economics (SP4TE) lab and I had the chance to collaborate with international laboratories, such as CERIAS of Purdue University and the Department of Electronics and Comm. Eng. of Tampere University of Technology. My research activity has focused on different fields, so that I could apply my knowledge as a computer engineer in both telecommunications and IT. In particular, I worked in the fields of Cognitive Radio Technology (CRT), Android-based app design and development, design and development for radio devices, Natural Language Processing & Sentiment Analysis, and Computer Vision. My passion for IT has led me to learn mobile programming and develop native mobile applications for Android and Windows Phone OS as an independent developer and freelancer for several companies. I'm also collaborating as an author with HTML.it, one of the most authoritative Italian websites on IT, to redact guides and articles about mobile programming. I'm currently working in the R&D team of Immobiliare.it SpA to develop novel tools for data processing and analyses for Immobiliare.it's products and our international partners.

Updated on June 14, 2022

Comments

  • antedesk
    antedesk almost 2 years

    I'm a beginner of asp.net jquery and html5 and I'm developing an asp.net mvc 4 site where I have a form with two Date fields. I don't want to insert a date manually, so I tried to use this solution to implement a simple datepicker:

         <fieldset>
        <legend>RangeDateViewModel</legend>
        <div class="editor-label">
            Start Date
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.StartDate,  new{ @class = "date" })
            @Html.ValidationMessageFor(model => model.StartDate)
        </div>
    
        <div class="editor-label">
            End Date
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.EndDate,  new{ @class = "date" })
            @Html.ValidationMessageFor(model => model.EndDate)
            </div>
    
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    
    
       }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    
    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/themes/base/css")
    
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".date").datepicker();
        });
    </script>
    }
    

    the code works good, but if I select a date from 13th until 30/31 th of the month i have always the same warning: "The field StartDate must be a date." and "The field EndDate must be a date."

    EDIT: I add my ViewModel as asked:

    public class RangeDateViewModel
    {
        public DateTime StartDate { get; set; }
    
        public DateTime EndDate { get; set; }
    
    }
    
  • antedesk
    antedesk about 11 years
    ehm sorry for the following silly question (i'm a newbi) but how do i change my code? because i try to use your code and i didn't use the datepicker; I tried to wrote $(".date").datepicker(); $.datepicker.setDefaults({ dateFormat: "dd/mm/yyyy" }); and it didn't work (always the same alert). Sorry
  • hazzik
    hazzik about 11 years
    datepicker uses 'y' for 2-digit years and 'yy' for 4-digits.
  • Jason Berkan
    Jason Berkan about 11 years
    @antedesk - What does your model look like? Can you add that in to your question?
  • Tony
    Tony about 11 years
    This does not answer his question, but I completely agree and love the Editor/Display templates in MVC. Antedesk, you may want to check them out to save you some time :D
  • InspiredBy
    InspiredBy about 11 years
    On the second thought I did address it. I provided a couple of different ways to format DateTime properly. Possibly you made the commend before some of my edits :)
  • Tony
    Tony about 11 years
    In your edit, not initially :) I upvoted this as you provided answer and the correct pattern for MVC to handle this situation :D link for more info: growingwiththeweb.com/2012/12/…
  • Graham
    Graham about 11 years
    What is the purpose of the virtual modifier on that prop?
  • antedesk
    antedesk about 11 years
    @JasonBerkan I add the view model to my question. thanks for your time
  • antedesk
    antedesk about 11 years
    Tony i'll do :D @Shenaniganz, thanks for your answar i'll try it (if my emulator decide to collaborate) anyway someone of you are able to answere to this other post of mine? stackoverflow.com/questions/16058760/… i had a problem working with double.
  • InspiredBy
    InspiredBy about 11 years
    @Graham oops, I forgot do delete it, copied from my Nhibernate entity. I'll delete it now.
  • Graham
    Graham about 11 years
    @Shenaniganz, Drats I was hoping that modifier did something secret and cool that I wasn't aware of :(