2013-07-02 41 views
8

我需要在EditorFor字段上使用datepicker。jQuery DatePicker MVC4 EditorFor

我的视图代码:

<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> 

脚本:

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

我不能使它发挥作用。我有以下错误:Microsoft JScript运行时错误:对象不支持此属性或方法'datepicker'。

我在尝试调用函数之前已经加载了jQuery。

+0

验证jQuery的顺序,你可以发布包括脚本在内的整个视图文件吗? – Overmachine

+0

你可以把你如何解决它? –

+1

我检查了我加载jquery的命令。然后我改变了TextForFForEditorForEditorFor。 – Rodrigo

回答

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

就不行,因为“EditorFor” 不会接受(一起传递给DOM)一类

所以,你需要使用“TextBoxFor”将接受一个类或更好的是,创建一个EditorTemplate来处理是一个DateTime任何字段并添加类有。 This link详细说明如何制作模板。

一旦你的类工作(可以在源代码中验证),其余的只是引用jquery代码。我用

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

并用你已有的脚本激活它。注意名称'.datepicker'与Class完全相同。

2

EditorFor接受类我

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

HTML标记

class="datepicker text-box single-line" 

类是工作。

+1

很好的回答:D,比选择的更好! –

0

我有一个simmilar问题,通过使用HTML5的功能解决了,那有日期时间的支持,在你的榜样,我建议尝试这样的财产以后:

<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> 

,我就将此唯一的事情就是一个类型=“datetime-local”