Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

asp.net mvc - How do you use the jQuery UI Datepicker with MVC's Html.TextBoxFor?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    });

Though I recommend using EditorFor instead.

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

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

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" } )%>

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"} )%>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...