Date only from TextBoxFor()

asp.net Mvc

asp.net Mvc Problem Overview


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.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

Solution 2 - asp.net Mvc

<%= Html.TextBoxFor(model => model.EndDate, new { @class = "jquery_datepicker", @Value = Model.EndDate.ToString("dd.MM.yyyy") })%>

Solution 3 - asp.net Mvc

[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

Then:

<%=Html.EditorFor(m => m.StartDate) %>

Solution 4 - asp.net Mvc

Or use the untyped helpers:

<%= Html.TextBox("StartDate", string.Format("{0:d}", Model.StartDate)) %>

Solution 5 - asp.net Mvc

This worked for me.

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

Solution 6 - asp.net Mvc

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

Solution 7 - asp.net Mvc

Don't be afraid of using raw HTML.

<input type="text" value="<%= Html.Encode(Model.SomeDate.ToShortDateString()) %>" />

Solution 8 - asp.net Mvc

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.

Solution 9 - asp.net Mvc

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>

Solution 10 - asp.net Mvc

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.

Solution 11 - asp.net Mvc

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.

Solution 12 - asp.net Mvc

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

Solution 13 - asp.net Mvc

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.

Solution 14 - asp.net Mvc

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

Solution 15 - asp.net Mvc

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

Solution 16 - asp.net Mvc

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

Solution 17 - asp.net Mvc

Just add next to your model.

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

Solution 18 - asp.net Mvc

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

Solution 19 - asp.net Mvc

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

Solution 20 - asp.net Mvc

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

Solution 21 - asp.net Mvc

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKronosView Question on Stackoverflow
Solution 1 - asp.net MvcRoss McNabView Answer on Stackoverflow
Solution 2 - asp.net MvcAlexeyssView Answer on Stackoverflow
Solution 3 - asp.net MvcKevin CraftView Answer on Stackoverflow
Solution 4 - asp.net MvcandersjanmyrView Answer on Stackoverflow
Solution 5 - asp.net Mvcuser5240713View Answer on Stackoverflow
Solution 6 - asp.net MvcLegendsView Answer on Stackoverflow
Solution 7 - asp.net MvcTamas CzinegeView Answer on Stackoverflow
Solution 8 - asp.net MvcAaronLSView Answer on Stackoverflow
Solution 9 - asp.net MvcScubaSteveView Answer on Stackoverflow
Solution 10 - asp.net MvcLiamView Answer on Stackoverflow
Solution 11 - asp.net MvcCrnaStenaView Answer on Stackoverflow
Solution 12 - asp.net MvctriskelionView Answer on Stackoverflow
Solution 13 - asp.net MvcguervenView Answer on Stackoverflow
Solution 14 - asp.net MvcudaView Answer on Stackoverflow
Solution 15 - asp.net MvccoymaxView Answer on Stackoverflow
Solution 16 - asp.net MvcYury DzhantuganovView Answer on Stackoverflow
Solution 17 - asp.net MvcarturasView Answer on Stackoverflow
Solution 18 - asp.net MvcMichael EmerickView Answer on Stackoverflow
Solution 19 - asp.net MvcSheriffView Answer on Stackoverflow
Solution 20 - asp.net MvcAeon SuenView Answer on Stackoverflow
Solution 21 - asp.net MvcJuan DIAZ SOTOView Answer on Stackoverflow