How to format a date in a two-way binding view in MVC 2?

So, let's say I have an idea about accessing a date:

<%= Html.TextBoxFor(model => Model.Birthday) %>

How can I determine how this date is formatted? I would like to use general formatting options , and it is important that this is a 2-way way (both for display and for data entry).

+3
source share
3 answers

ViewModel, , , . , , . ViewModel, .

+2

System.ComponentModel.DataAnnotations, , . ,

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

Then, in your view, use:
<%= Html.EditorFor(model => model.Birthday) %>

, HTML , Html.EditorFor.

+4

, , Html.EditorFor(). EditorTemplates.

.

> > EditorTemplates

Add a new MVC 2 control to the EditorTemplates folder and name it DateTime.ascx. Html.EditorFor (DateTime) will now use this user control for display.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime?>" %>
<%= Html.TextBox(string.Empty, (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty)) %>
0
source

Source: https://habr.com/ru/post/1738980/


All Articles