ChatGPT解决这个技术问题 Extra ChatGPT

Date only from TextBoxFor()

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.


R
Ross McNab

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

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" })
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).
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?
I'm buying you a beer! This small issue caused me such a headache until I found this answer.
FYI: Many browsers and the input[type=date] spec require "{0:yyyy-MM-dd}" format.
A
Alexeyss
<%= Html.TextBoxFor(model => model.EndDate, new { @class = "jquery_datepicker", @Value = Model.EndDate.ToString("dd.MM.yyyy") })%>

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.
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.
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"))
@Spikolynn, this did not generate a second 'Value' attribute for me (MVC3/razor template).
IMORTANT: Check for Capital "V" in "Value", small letter wont do!
k
kim3er
[DisplayName("Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime StartDate { get; set; }

Then:

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

Yes, as now there is the EditorFor helper and MVC2 is finalized, your solution is the way to go
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.
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()
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
@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.
a
andersjanmyr

Or use the untyped helpers:

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

Slight variation @Html.TextBoxFor(model => model.EndDate, "{0:d}", new { type = "date" })
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.
@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)
Can you create a new issue and detail what you've done. Tag me and I'll be happy to help.
This solution is the best when you need globalization.
T
Tasos K.

This worked for me.

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

L
Legends

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:

https://i.stack.imgur.com/m2HPP.png

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

small thing, missing flower braces at the last
T
Tamas Czinege

Don't be afraid of using raw HTML.

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

How would he post it back then? Because date only almost certainly won't get parsed back on the server.
As long as you include the proper 'name="StartDate"' the model binder will pick it up.
@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
T
Tasos K.

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.


T
Tasos K.

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>

L
Liam

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.


C
CrnaStena

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.


t
triskelion

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

g
guerven

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.


S
Sneha

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

c
coymax

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


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.
Y
Yury Dzhantuganov

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

a
arturas

Just add next to your model.

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

M
Michael Emerick

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

S
Sheriff

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

E
Elijan9

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

D
Dr. Mantis Tobbogan
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" })

Please add some explanation to your code. Code only answers are discouraged on SO.

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now