286

I'm having trouble displaying the only date part of a DateTime into a textbox using TextBoxFor<,>(expression, htmlAttributes).

The model is based on Linq2SQL, field is a DateTime on SQL and in the Entity model.

Failed:

<%= Html.TextBoxFor(model => model.dtArrivalDate, String.Format("{0:dd/MM/yyyy}", Model.dtArrivalDate))%>

This trick seems to be depreciated, any string value in the object htmlAttribute is ignored.

Failed:

[DisplayFormat( DataFormatString = "{0:dd/MM/yyyy}" )]
public string dtArrivalDate { get; set; }

I would like to store and display only the date part on the details/edit view, without the "00:00:00" part.

1

22 Answers 22

381

MVC4 has solved this problem by adding a new TextBoxFor overload, which takes a string format parameter. You can now simply do this:

@Html.TextBoxFor(m => m.EndDate, "{0:d MMM yyyy}")

There's also an overload that takes html attributes, so you can set the CSS class, wire up datepickers, etc:

@Html.TextBoxFor(m => m.EndDate, "{0:d MMM yyyy}", new { @class="input-large" })
5
  • 40
    This is the best answer for MVC4 - it allows me to use jquery UI datepicker and formats the selection doing this:@Html.TextBoxFor(m => m.SomeDate, "{0:MM/dd/yyyy}", new { @id="datepicker" })
    – ericb
    Apr 14, 2013 at 18:46
  • 3
    Thank you! But it seems like a bug that TextBoxFor ignores the model's [DisplayFormat] attribute. Glad there's at least an override in TextBoxFor (and that you alerted me to it). Sep 18, 2013 at 0:40
  • 7
    I set it like this @Html.TextBoxFor(model => model.CDate, "{0:dd.MM.yyyy}") but on httpPost I get data like MM.dd.yyyy. How to solve this?
    – user007
    Jan 17, 2014 at 19:13
  • Doesn't work for me. I need to be able to read in the date in two ways from an MVC form, MM/dd/yyyy or dd/MM/yyyy. Even though I set it as you did above (but with my formats), it will never read in dd/MM/yyyy format, it returns a null.
    – astrosteve
    Apr 15, 2016 at 21:32
  • 5
    FYI: Many browsers and the input[type=date] spec require "{0:yyyy-MM-dd}" format.
    – KyleMit
    Sep 19, 2016 at 14:28
258
<%= Html.TextBoxFor(model => model.EndDate, new { @class = "jquery_datepicker", @Value = Model.EndDate.ToString("dd.MM.yyyy") })%>
12
  • 5
    The EditorFor solution works, except when you need to override other HTML attributes like the id or class. This is a great solution. Strange that the V needs to be upper case.
    – Ben Mills
    Jul 17, 2012 at 3:30
  • 1
    To handle null safely, you could do Model.EndDate.GetValueOrDefault().ToString("dd.MM.yyyy"). The default value of Datetime will be displayed if Model.EndDate is null.
    – user1026130
    Feb 22, 2013 at 14:46
  • 15
    Regarding nulls, the default value of DateTime is January 1st of 1901, in my opinion, it would be better to use @Value = (Model.DateBecamePermanentResident == null ? "" : Model.DateBecamePermanentResident.Value.ToString("dd.MM.yyyy"))
    – Serj Sagan
    May 25, 2013 at 2:31
  • 2
    @Spikolynn, this did not generate a second 'Value' attribute for me (MVC3/razor template).
    – Doug S
    Sep 22, 2013 at 21:12
  • 2
    IMORTANT: Check for Capital "V" in "Value", small letter wont do! Aug 27, 2014 at 6:57
242
[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

Then:

<%=Html.EditorFor(m => m.StartDate) %>
10
  • 71
    But now the Jquery UI datepicker can't be applied to this input, because it is ignoring my @class="datepicker" attributes as specified to the Html.EditorFor() helper. So this textbox now formats correctly, but doesn't launch a datepicker when clicked. So its fixed one thing and broken another.
    – Aaron
    Feb 17, 2011 at 0:05
  • 6
    How can I get it to display in line with this solution, but also have it launch the datepicker like it did with Html.TextboxFor()
    – Aaron
    Feb 17, 2011 at 0:06
  • 50
    I am using MVC4 Razor syntax, the date field is rendered as @Html.EditorFor(m => m.IssueDate) and the formatting on the model is applied as [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}" )] but the date is still shown as 01/01/0001 12:00:00 AM
    – bjan
    Mar 6, 2012 at 6:49
  • 4
    @Aaron There is no overload of EditorFor that has an htmlAttributes parameter. You're probably passing it into the viewTemplate parameter or something, thinking you were passing htmlAttributes. This is the disadvantage of Editorfor. TextBoxFor ignores DisplayFormat annotation. Alexeyss's solution applies the format differently to work around this.
    – AaronLS
    Oct 18, 2012 at 22:05
  • 1
    NOTE: you HAVE TO use both DisplayFormat and EditorFor at the same time for it to work (with Razor engine, anyways). Using DisplayFormat with TextBoxFor did not work for me. Jan 4, 2019 at 21:36
48

Or use the untyped helpers:

<%= Html.TextBox("StartDate", string.Format("{0:d}", Model.StartDate)) %>
7
  • 23
    Slight variation @Html.TextBoxFor(model => model.EndDate, "{0:d}", new { type = "date" }) Oct 24, 2012 at 17:30
  • It does use Razor instead of ASPX view engine, but they both work in MVC 4 and changing from one syntax to the other is trivial. I posted in Razor cause that's what I used and tested with. Like I said, it's a variation. May 13, 2013 at 16:57
  • 1
    @Dan Friedman : This was the way to go for me! I used to work with an editor template, but then I also had to create my own html and also include all the validation messages AND all the Bootstrap attributes, so this is realy the way to go for me (asp.net mvc5)
    – Michel
    May 23, 2014 at 11:00
  • 1
    Can you create a new issue and detail what you've done. Tag me and I'll be happy to help. May 31, 2014 at 11:49
  • 1
    This solution is the best when you need globalization. Apr 16, 2015 at 20:46
27

This worked for me.

@Html.TextBoxFor(m => m.DateOfBirth, "{0:MM/dd/yyyy}", new { size = "12", @class = "DOB", tabindex = 121 })
0
27

TL;DR;

@Html.TextBoxFor(m => m.DOB,"{0:yyyy-MM-dd}", new { type = "date" })

Applying [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] didn't work out for me!


Explanation:

The date of an html input element of type date must be formatted in respect to ISO8601, which is: yyyy-MM-dd

The displayed date is formatted based on the locale of the user's browser, but the parsed value is always formatted yyyy-mm-dd.

My experience is, that the language is not determined by the Accept-Language header, but by either the browser display language or OS system language.

In order to display a date property of your model using Html.TextBoxFor:

enter image description here

Date property of your model class:

public DateTime DOB { get; set; }

Nothing else is needed on the model side.


In Razor you do:

@Html.TextBoxFor(m => m.DOB,"{0:yyyy-MM-dd}", new { type = "date" })
1
  • 2
    small thing, missing flower braces at the last Aug 28, 2020 at 15:21
12

Don't be afraid of using raw HTML.

<input type="text" value="<%= Html.Encode(Model.SomeDate.ToShortDateString()) %>" />
3
  • 4
    How would he post it back then? Because date only almost certainly won't get parsed back on the server. Feb 27, 2010 at 7:16
  • 10
    As long as you include the proper 'name="StartDate"' the model binder will pick it up.
    – naspinski
    Dec 7, 2011 at 22:51
  • @DrJokepu the only thing that worker for me on MVC3. That is I failed to make TextBoxFor or EditorFor format value anyhow. See my question: TextBoxFor helper mixes day and month in dates
    – horgh
    Apr 11, 2013 at 7:08
4

You can also use the HTML 5 attributes by applying this data annotation:

[DataType(DataType.Date)]

But the problem is this enables a browser specific date picker for HTML 5 browsers. You still need your own date picker for browsers without support, and then you have to make sure your date picker doesn't appear in addition to a browser's (Modernizr can do this easily), or hide the browser's if it does(complicated and I don't know how reliable methods I saw were).

In the end I went with Alex's because my current environment doesn't have Modernizr, but if it did, I would have used that to conditionally only show my data picker if the browser didn't support one already.

3

For me, I needed to keep the TextboxFor() because using EditorFor() changes the input type to date. Which, in Chrome, adds a built in date picker, which screwed up the jQuery datepicker that I was already using. So, to continue using TextboxFor() AND only output the date, you can do this:

<tr>
    <td class="Label">@Html.LabelFor(model => model.DeliveryDate)</td>
    @{
        string deliveryDate = Model.DeliveryDate.ToShortDateString();
    }
    <td>@Html.TextBoxFor(model => model.DeliveryDate, new { @Value = deliveryDate }) *</td>
    <td style="color: red;">@Html.ValidationMessageFor(model => model.DeliveryDate)</td>
</tr>
3

I use Globalize so work with many date formats so use the following:

@Html.TextBoxFor(m => m.DateOfBirth, "{0:d}")

This will automatically adjust the date format to the browser's locale settings.

2

Keep in mind that display will depend on culture. And while in most cases all other answers are correct, it did not work for me. Culture issue will also cause different problems with jQuery datepicker, if attached.

If you wish to force the format escape / in the following manner:

@Html.TextBoxFor(model => model.dtArrivalDate, "{0:MM\\/dd\\/yyyy}")

If not escaped for me it show 08-01-2010 vs. expected 08/01/2010.

Also if not escaped jQuery datepicker will select different defaultDate, in my instance it was May 10, 2012.

1

The DisplayFormat attribute did not work for me in either form upon initial load. I created an EditorTemplate instead:

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

The Template Editor will work for display purposes only. If you use the same editor (which makes sense because its an editor) and you supplied a value like 31/01/2010 - you'll get an error message saying the format is invalid.

1

If you are using Bootstrap date picker, then you can just add data_date_format attribute as below.

      @Html.TextBoxFor(m => m.StartDate, new { 
@id = "your-id", @class = "datepicker form-control input-datepicker", placeholder = "dd/mm/yyyy", data_date_format = "dd/mm/yyyy" 
})
0

// datimetime displays in the datePicker is 11/24/2011 12:00:00 AM

// you could split this by space and set the value to date only

Script:

    if ($("#StartDate").val() != '') {
        var arrDate = $('#StartDate').val().split(" ");
        $('#StartDate').val(arrDate[0]);
    }

Markup:

    <div class="editor-field">
        @Html.LabelFor(model => model.StartDate, "Start Date")
        @Html.TextBoxFor(model => model.StartDate, new { @class = "date-picker-needed" })
    </div>

Hopes this helps..

1
  • 7
    Your solution should work. But in my humble opinion, it may be dangerous to rely on client side on the formated string date issued in server side. If regional settings on server side does not include a space between date and time, your exposed solution will fail.
    – Kronos
    Nov 14, 2011 at 15:57
0

Sure you can use Html.EditorFor. But if you want to use TextBoxFor and use format from DisplayFormat attribute you can use it in this way:

@Html.TextBoxFor(model => model.dtArrivalDate, ModelMetadata.FromLambdaExpression(model => model.dtArrivalDate, ViewData).EditFormatString)

or create next extension:

public static class HtmlExtensions
{
    public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        return htmlHelper.TextBoxFor(expression, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).EditFormatString, htmlAttributes);
    }
}
0

Just add next to your model.

[DataType(DataType.Date)]
public string dtArrivalDate { get; set; }
0

When using tag helpers in ASP.NET Core, the format needs specified in ISO format. If not specified as such, bound input data won't display properly and will show as mm/dd/yyyy with no value.

Model:

[Display(Name = "Hire")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? HireDate { get; set; }

View:

<input asp-for="Entity.HireDate" class="form-control" />

The format can also be specified in the view using the asp-format attribute.

The resulting HTML will look as follows:

<input class="form-control" type="date" id="Entity_HireDate" 
    name="Entity.HireDate" value="2012-01-01">
0

You can use below code to print time in HH:mm format, In my case Property type is TimeSpan So the value is coming in HH:mm:tt format but I have to show in above format ie. HH:mm

So you can use this code:

@Html.TextBoxFor(x =>x.mTimeFrom, null, new {@Value =Model.mTimeFrom.ToString().Substring(0,5), @class = "form-control success" })
0

If you insist on using the [DisplayFormat], but you are not using MVC4, you can use this:

@Html.TextBoxFor(m => m.EndDate, new { Value = @Html.DisplayFor(m=>m.EndDate), @class="datepicker" })
0
0
net Razor problems DateTime


Models
public class UsuarioFecha
{
       [DataType(DataType.DateTime)]
        [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
        public DateTime? dateXXX { get; set; }
}

view

@model proyect.Models.UsuarioFecha

   @Html.TextBoxFor(m => m.dateXXX , new { Value = @Html.DisplayFor(m => m.dateXXX ), @class = "form-control", @type = "date" })
1
  • Please add some explanation to your code. Code only answers are discouraged on SO.
    – Pankwood
    Dec 18, 2020 at 16:29
0

[DataType(DataType.Date)]

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]

public DateTime? fieldname { get; set; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.