PatW
PatW

Reputation: 141

TextBoxFor unwanted modification of its default DateTime value format

I am currently developping a web application using ASP.NET MVC 4. Here is a description of the problem I am facing :

I created a strongly-typed view in order to edit some fields of a table, and in particular a DateTime field. What I want to do is to display a textbox with the default value retrieved from the database using the following code :

@Html.TextBoxFor(m => m.Date, new { @Value = ViewBag.DefaultValue })

where ViewBag.DefaultValue is set in the Controller using a simple query. Since I am talking about dates, I also have added this in my web.config :

<globalization uiCulture="fr-Fr" culture="fr-FR" />

Now the fun part is that, when displayed, the date has a MM/DD/YYYY format instead of a DD/MM/YYYY one, which is the one saved in the database. Moreover, when I just want to display the ViewBag.DefaultValue in a div, it shows the correct format, ie DD/MM/YYYY.

Has anyone faced some similar issues? I can understand that my description can be rather vague, but I really don't understand what is going on there.

Thanks in advance.

Upvotes: 2

Views: 964

Answers (2)

PatW
PatW

Reputation: 141

I tried it, but without any success.

After a while of checking, I finally found a solution there : http://geekswithblogs.net/80n/archive/2012/04/27/apply-a-datetime-format-in-an-asp.net-mvc-textboxfor.aspx

Using EditorFor and data annotation could not work as I need to link this tag to a datepicker event. So I used the second solution.

The trick consists in forcing the format when the value is passed : @Html.TextBoxFor( m => m.Date, new {@Value = Model.Date.ToString("dd/MM/yyyy")}

Hope this can help.

Upvotes: 1

Stephen Reindl
Stephen Reindl

Reputation: 5819

I use something like this in global.aspx.cs:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-us");
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-us");
}

to prevent functions not using correct settings.

Upvotes: 0

Related Questions