Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery DatePicker MVC4 EditorFor

I need to use datepicker on an EditorFor field.

My code for the view is:

<div class="editor-label">
    @Html.Label("birthDate","birthDate")
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.birthDate, new { @class = "datepicker"})
    @Html.ValidationMessageFor(model => model.birthDate)
</div>

The script:

<script type="text/javascript">
$(document).ready(
    function () {
        $('.datepicker').datepicker({
            changeMonth: true,
            changeYear: true,
            minDate: "-99Y",
            dateFormat: "dd/mm/yyyy"
        });
    });

I can't make it work. I have the following error: Microsoft JScript runtime error: Object doesn't support this property or method 'datepicker'.

I have already loaded jQuery before I try to call the function.

like image 475
Rodrigo Avatar asked Jul 02 '13 13:07

Rodrigo


3 Answers

@Html.EditorFor(model => model.birthDate, new { @class = "datepicker"})

Will not work, because "EditorFor" will not accept (pass along to the DOM) a Class.

So, you need to use "TextBoxFor" which will accept a Class or better yet, create an EditorTemplate to handle any field that is a DateTime and add the class there. This link details how to make the Template.

Once you have the Class working (can be verified in the source code), the rest is just referencing the jquery code. I use

@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryui")

and activating it with the script you already have. Watch that the name '.datepicker' is Exactly the same as the Class.

like image 193
Greg Little Avatar answered Nov 09 '22 14:11

Greg Little


EditorFor accept a class for me

@Html.EditorFor(model => model.Birthday, new { htmlAttributes = new { @class = "datepicker",@Name="birthday",@PlaceHolder = "mm/dd/yyyy" } })

Html markup

class="datepicker text-box single-line"

The Class is work.

like image 4
Julian89757 Avatar answered Nov 09 '22 14:11

Julian89757


I had a simmilar issue, solved by using the HTML5 functionality, that has support for datetime, in your example I would suggest trying somthing like this:

<div class="editor-label">
    @Html.Label("birthDate","birthDate")
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.birthDate, new { @class = "datepicker", type="datetime-local"})
    @Html.ValidationMessageFor(model => model.birthDate)
</div>

the only thing that I addes is a type ="datetime-local"

like image 1
Goran.Mards Avatar answered Nov 09 '22 14:11

Goran.Mards