Why is the date format in ASP NET MVC different when used inside the Html Helper?

I came across a very interesting problem. If I use ViewData to pass the DateTime value to the view and then display it inside the text field, even if I use String.Format in the same way, I get different formatting results when using the Html.TextBox helper.

<%= Html.TextBox("datefilter", String.Format("{0:d}", ViewData["datefilter"]))%>
<input id="test" name="test" type="text" value="<%: String.Format("{0:d}", ViewData["datefilter"]) %>" />

The above code displays the following html:

<input id="datefilter" name="datefilter" type="text" value="2010-06-18" />
<input id="test" name="test" type="text" value="18/06/2010" />

Notice how the first line using the Html helper creates the date format in one way, and the second in a very different way. Any ideas why?

Note. I am now in Brazil, so the standard format for short dates here is dd / MM / yyyy.

+3
source share
1 answer

, TextBox , ViewData["datefilter"], datefilter , , . .

- ViewData. .

:

public class MyModel
{
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", 
                   ApplyFormatInEditMode = true)]
    public DateTime Date { get; set; }
}

:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyModel
        {
            Date = DateTime.Now
        };
        return View(model);
    }
}

:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SomeNs.Models.MyModel>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%: Html.EditorFor(x => x.Date) %>
</asp:Content>
+9

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


All Articles