0

How to implement EditorFor DateTime?

I already have editors for Date and Time separately. Can I use it for my DateTime editor?

Are there any suggestions, how to do it?

Date editor:

@model DateTime

@Html.TextBox(string.Empty, (Model != default(DateTime) ? Model.ToShortDateString() : string.Empty), new { @class = "date form-control" })

Time editor:

@model DateTime?

@Html.TextBox(string.Empty, (Model.HasValue ? Model.Value.ToString("HH:mm") : string.Empty), new { @class = "time form-control" })

I am using jQuery UI datepicker for date editor. Timepicker is also jQuery plugin.

6
  • Can't you just combine them? For example @Html.EditorFor(Model.TheDate) - @Html.EditorFor(Model.TheTime). Do you need different formats? Commented Feb 4, 2014 at 9:37
  • @AndreiV this will generate two inputs... not great for model binding, I would say. Commented Feb 4, 2014 at 9:38
  • Could you show the code of your Date and Time editors ? Maybe you can do some refactoring, or use a custom HtmlHelper instead of Templates... Commented Feb 4, 2014 at 9:39
  • @RaphaëlAlthaus, add a hidden then? Commented Feb 4, 2014 at 9:39
  • @AndreiV Yes, everything's possible, but then you'll need some javascript to populate that hidden field. It's not really pure "reuse" of existing... Commented Feb 4, 2014 at 9:41

2 Answers 2

4

Create DateTime.cshtml in Views/Shared/EditorTemplates that contains:

@inherits System.Web.Mvc.WebViewPage<System.DateTime?>
@Html.TextBox("", string.Format("{0:yyyy-MM-dd HH:mm}", 
              Model.HasValue ? Model : null), new { @class = "dateTimePicker" })

And use some jquery datepicker. think this one works with default jquery ui one.

Sign up to request clarification or add additional context in comments.

Comments

0

Can I use it for my DateTime editor?

With this JQuery TimePicker plugin you can definitely have one Editor field.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.