简体   繁体   中英

MVC3 Date in UK Format not received on Controller

Given this VM

public class ApplicationDTO : BaseDTO
{
    public DateTime Date { get; set; }
    public int JobId {get;set;}
    public int Status {get;set;}
    [Required]
    public string Message { get; set; }
    public string ExpertCode { get; set; }
}

I have a hidden field thusly

@Html.Hidden("Date", DateTime.Now)

Which fiddler shows me is sent to the server as I would expect (UK format, I'm in the UK!)

在此输入图像描述

But on the controller the date shows as being the default min. date

在此输入图像描述

Is it just the UK format? If so, what is my best way round it? Whilst currently I am setting it to the current date, potentially it could be set to any given date ie

@Html.HiddenFor(x => x.Date)

I am using AJAX to submit the form, if that makes a difference.

If it is a Get MVC uses culture invariant format (Basically US format) by default during model binding. So it doesn't accept UK date format. I believe the design reasons are that a querystring could be passed around so therefore it needs to be culture invariant (I wasn't 100% convinced by that logic).

This article covers a possible solution http://xhalent.wordpress.com/2011/05/14/localization-of-dates-in-asp-net-mvc/

We just make sure we never do a Get with a UK date format

This questions also covers the issue Globalization problem with DateTime and ASP.NET MVC 3 Model Binding

you should use Data Annotation for Formatting the date on your Model or View model

public class ApplicationDTO : BaseDTO
{
   [DisplayFormat(DataFormatString="{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
   public DateTime Date { get; set; }
   public int JobId {get;set;}
   public int Status {get;set;}
   [Required]
   public string Message { get; set; }
   public string ExpertCode { get; set; }
}

Apply the format according you. As i have seen you are not providing any format to your property

我在dd.MM.yyyy格式中遇到了类似的问题,并且必须将web.config中的globalization元素设置为适当的culture和uiCulture属性设置。

If you use @Html.Hidden (not the For helper) it won't be able to match the parameter in the request to the property in your model.

If you use @Html.HiddenFor(x=>x.Date, "28/2/2013") you will see the date populated appropriately.

Also you can verify the Request.Params collection. Put a break point in the Action. You'll see that one of the Params has your date.... JQuery does not affect this in any way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM