0

I'm trying to follow this example to correctly apply datetime format

I have view model which contains datetime property

public class MyViewModel {
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy HH:mm:ss}")]
    public DateTime Starting { get; set; }
}

inside view I have form

@using (Html.BeginForm(null, null, null, FormMethod.Post, new { @id = "myForm", @name = "myForm" }))
{
    ...   
<div class="form-group">
   @Html.LabelFor(model => model.Starting, htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
       @Html.EditorFor(model => model.Starting, new { htmlAttributes = new { @class = "dateTimePicker" } })
       @Html.ValidationMessageFor(model => model.Starting, "", new { @class = "text-danger" })
     </div>
</div>
}

and on the same page inside scripts section

    <script>
       jQuery.validator.addMethod("MyDateTimeFormat", function (value, element) {
            return Date.parseExact(value, "dd.MM.yyyy HH:mm:ss");    
        }, "Please provide correct datetime format!");

        var form = $("#myForm");
        form.validate({
            rules: {
                Starting: { MyDateTimeFormat: true }
            }
        });
        $("#myForm").submit(function () {            
            if (form.valid())
               alert("The form is valid: \n" + Date.parse($("#Starting").val()));
                $("#Starting").val() = Date.parse($("#Starting").val());
            else {
                alert("Valid: " + form.valid());
            }
        });
    </script>

Date format is correctly applied but after submitting form on the HttpPost action inside controller I'm getting MyViewModel.Starting with default value 01/01/0001 not the one which is selected at the view. What I'm doing wrong?

Edit: Added into Global.asax.cs

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    string cultureName = CultureHelper.GetImplementedCulture("de-DE");
    Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
    Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
user1765862
  • 13,635
  • 28
  • 115
  • 220
  • This looks like an culture problem. Please ensure that the data send to the server can be parsed on the server side. You should have a look with fiddler what is actually transferred. In all cases you should try to send the information in a neutral format (i.e. yyyy-MM-dd HH:mm:ss) – Stephen Reindl Apr 23 '15 at 18:33
  • what do you suggest? The whole point is to format datetime in this specific format. Should I converting in default format on the fly just before sending, if so how. Thanks – user1765862 Apr 23 '15 at 18:37

1 Answers1

1

.NET is parsing dates (and numbers) according to the current culture set. The culture in ASP.NET depends not on the browsers culture but on the culture the ASP.NET thread is running. So if you want to pass dates in a specific format there are (at least) two options:

  1. Set the current thread's culture (or at least the date format) to a specific value. For example (this should match your example):

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        string cultureName = CultureHelper.GetImplementedCulture("de-DE"); 
        Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    }
    

    please find CultureHelper from here and do not forget to add your supported languages (see list _cultures).

  2. Create a model binder that filters DateTime fields according to your needs. An example can be found here.

EDIT: Updated example

Community
  • 1
  • 1
Stephen Reindl
  • 5,659
  • 2
  • 34
  • 38
  • I tried with adding System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); in the HttpGet action before sending viewmodel to the view. Not helped. Can you please be more specific? – user1765862 Apr 23 '15 at 19:31
  • You have to put it to `Application_BeginRequest` (for example). I've updated my code example above... – Stephen Reindl Apr 23 '15 at 19:33
  • can you please post and CultureHelper as well. Thank you. – user1765862 Apr 23 '15 at 19:39
  • uh, sorry, please have a look at http://afana.me/post/aspnet-mvc-internationalization-part-2.aspx (search for CultureHelper). I've just copied the code from one of our applications, therefore this part was missing. – Stephen Reindl Apr 23 '15 at 19:41
  • ok, I added CultureHelper. Since I'm using mvc5 I added your code snippet into Global.asax.cs inside Application_Start method. Nothing changed. Should I move from Appliaction_Start and somewhere else maybe? – user1765862 Apr 23 '15 at 19:48
  • I added into Application_BeginRequest update the question with your code snippet, still doesnt work. Am I doing something wrong. I manually put Application_BeginRequest into global.asax.cs since it wasnt there. – user1765862 Apr 23 '15 at 19:58
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/76102/discussion-between-stephen-reindl-and-user1765862). – Stephen Reindl Apr 23 '15 at 20:02