您如何将 jQuery UI Datepicker 与 MVC 的 Html.TextBoxFor 一起使用? [英] How do you use the jQuery UI Datepicker with MVC's Html.TextBoxFor?

查看:16
本文介绍了您如何将 jQuery UI Datepicker 与 MVC 的 Html.TextBoxFor 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架的模型绑定,并有一个 Html.TextBoxFor(model =>model.date) 输入.我知道如何告诉 jQuery 如何实现日期选择器,但不是在这种情况下.我需要在此处添加什么才能在用户输入此字段时弹出日历?

I am using Model binding with the Entity Framework and have an Html.TextBoxFor(model =>model.date) input. I know how to tell jQuery how to implement a datepicker but not in this context. What would I need to add here to have a calendar popup when the user enters this field?

推荐答案

您需要使用 HtmlHelper 重载,它允许您指定 Html 属性.然后使用 jquery 选择器定位它们.

You'll want to use the HtmlHelper overload that allows you to specify Html attributes. Then target them with the jquery selector.

// in view
<%= Html.TextBoxFor(x => x.Date, new { @class="datepicker" })%>

// in js
$(document).ready({
         $('.datepicker').datepicker();
    });

虽然我建议使用 EditorFor 代替.

Though I recommend using EditorFor instead.

<%= Html.EditorFor(x => x.Date)%>

您可以创建一个 EditorTemplate 来处理任何 DateTime 字段并让它输出正确的字段.

You can create an EditorTemplate to handle any field that is a DateTime and have it output the proper field.

创建 /Views/Shared/EditorTemplates/DateTime.ascx 并将其放入其中...

Create /Views/Shared/EditorTemplates/DateTime.ascx and put this in it...

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>    
<%= Html.TextBox("", Model.ToShortDateString(), new { @class="datepicker" } )%>

或者如果您需要允许 DateTime 为空值:

Or if you need to allow DateTime's with nulls:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>    
<%= Html.TextBox("", (Model.HasValue? Model.Value.ToShortDateString():""), new { @class="datepicker"} )%>

如果您想修改视图中处理日期时间的方式,您可以随时使用 EditorFor 并使用中央 ascx 进行编辑.

Then you can always use EditorFor and have a central ascx to edit if you ever want to modify the way date times are handled in your views.

这篇关于您如何将 jQuery UI Datepicker 与 MVC 的 Html.TextBoxFor 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆