天道酬勤,学无止境

MVC DateTime binding with incorrect date format

Asp.net-MVC now allows for implicit binding of DateTime objects. I have an action along the lines of

public ActionResult DoSomething(DateTime startDate) 
{ 
... 
}

This successfully converts a string from an ajax call into a DateTime. However, we use the date format dd/MM/yyyy; MVC is converting to MM/dd/yyyy. For example, submitting a call to the action with a string '09/02/2009' results in a DateTime of '02/09/2009 00:00:00', or September 2nd in our local settings.

I don't want to roll my own model binder for the sake of a date format. But it seems needless to have to change the action to accept a string and then use DateTime.Parse if MVC is capable of doing this for me.

Is there any way to alter the date format used in the default model binder for DateTime? Shouldn't the default model binder use your localisation settings anyway?

评论

I've just found the answer to this with some more exhaustive googling:

Melvyn Harbour has a thorough explanation of why MVC works with dates the way it does, and how you can override this if necessary:

http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx

When looking for the value to parse, the framework looks in a specific order namely:

  1. RouteData (not shown above)
  2. URI query string
  3. Request form

Only the last of these will be culture aware however. There is a very good reason for this, from a localization perspective. Imagine that I have written a web application showing airline flight information that I publish online. I look up flights on a certain date by clicking on a link for that day (perhaps something like http://www.melsflighttimes.com/Flights/2008-11-21), and then want to email that link to my colleague in the US. The only way that we could guarantee that we will both be looking at the same page of data is if the InvariantCulture is used. By contrast, if I'm using a form to book my flight, everything is happening in a tight cycle. The data can respect the CurrentCulture when it is written to the form, and so needs to respect it when coming back from the form.

I would globally set your cultures. ModelBinder pick that up!

  <system.web>
    <globalization uiCulture="en-AU" culture="en-AU" />

Or you just change this for this page.
But globally in web.config I think is better

I've been having the same issue with short date format binding to DateTime model properties. After looking at many different examples (not only concerning DateTime) I put together the follwing:

using System;
using System.Globalization;
using System.Web.Mvc;

namespace YourNamespaceHere
{
    public class CustomDateBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext", "controllerContext is null.");
            if (bindingContext == null)
                throw new ArgumentNullException("bindingContext", "bindingContext is null.");

            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value == null)
                throw new ArgumentNullException(bindingContext.ModelName);

            CultureInfo cultureInf = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            cultureInf.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

            try
            {
                var date = value.ConvertTo(typeof(DateTime), cultureInf);

                return date;
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
                return null;
            }
        }
    }

    public class NullableCustomDateBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext", "controllerContext is null.");
            if (bindingContext == null)
                throw new ArgumentNullException("bindingContext", "bindingContext is null.");

            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value == null) return null;

            CultureInfo cultureInf = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            cultureInf.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

            try
            {
                var date = value.ConvertTo(typeof(DateTime), cultureInf);

                return date;
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
                return null;
            }
        }
    }
}

To keep with the way that routes etc are regiseterd in the Global ASAX file I also added a new sytatic class to the App_Start folder of my MVC4 project named CustomModelBinderConfig:

using System;
using System.Web.Mvc;

namespace YourNamespaceHere
{
    public static class CustomModelBindersConfig
    {
        public static void RegisterCustomModelBinders()
        {
            ModelBinders.Binders.Add(typeof(DateTime), new CustomModelBinders.CustomDateBinder());
            ModelBinders.Binders.Add(typeof(DateTime?), new CustomModelBinders.NullableCustomDateBinder());
        }
    }
}

I then just call the static RegisterCustomModelBinders from my Global ASASX Application_Start like this:

protected void Application_Start()
{
    /* bla blah bla the usual stuff and then */

    CustomModelBindersConfig.RegisterCustomModelBinders();
}

An important note here is that if you write a DateTime value to a hiddenfield like this:

@Html.HiddenFor(model => model.SomeDate) // a DateTime property
@Html.Hiddenfor(model => model) // a model that is of type DateTime

I did that and the actual value on the page was in the format "MM/dd/yyyy hh:mm:ss tt" instead of "dd/MM/yyyy hh:mm:ss tt" like I wanted. This caused my model validation to either fail or return the wrong date (obviously swapping the day and month values around).

After a lot of head scratching and failed attempts the solution was to set the culture info for every request by doing this in the Global.ASAX:

protected void Application_BeginRequest()
{
    CultureInfo cInf = new CultureInfo("en-ZA", false);  
    // NOTE: change the culture name en-ZA to whatever culture suits your needs

    cInf.DateTimeFormat.DateSeparator = "/";
    cInf.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
    cInf.DateTimeFormat.LongDatePattern = "dd/MM/yyyy hh:mm:ss tt";

    System.Threading.Thread.CurrentThread.CurrentCulture = cInf;
    System.Threading.Thread.CurrentThread.CurrentUICulture = cInf;
}

It won't work if you stick it in Application_Start or even Session_Start since that assigns it to the current thread for the session. As you well know, web applications are stateless so the thread that serviced your request previously is ot the same thread serviceing your current request hence your culture info has gone to the great GC in the digital sky.

Thanks go to: Ivan Zlatev - http://ivanz.com/2010/11/03/custom-model-binding-using-imodelbinder-in-asp-net-mvc-two-gotchas/

garik - https://stackoverflow.com/a/2468447/578208

Dmitry - https://stackoverflow.com/a/11903896/578208

It going to be slightly different in MVC 3.

Suppose we have a controller and a view with Get method

public ActionResult DoSomething(DateTime dateTime)
{
    return View();
}

We should add ModelBinder

public class DateTimeBinder : IModelBinder
{
    #region IModelBinder Members
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        DateTime dateTime;
        if (DateTime.TryParse(controllerContext.HttpContext.Request.QueryString["dateTime"], CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dateTime))
            return dateTime;
        //else
        return new DateTime();//or another appropriate default ;
    }
    #endregion
}

and the command in Application_Start() of Global.asax

ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());

It is also worth noting that even without creating your own model binder multiple different formats may be parsable.

For instance in the US all the following strings are equivalent and automatically get bound to the same DateTime value:

/company/press/may%2001%202008

/company/press/2008-05-01

/company/press/05-01-2008

I'd strongly suggest using yyyy-mm-dd because its a lot more portable. You really dont want to deal with handling multiple localized formats. If someone books a flight on 1st May instead of 5th January you're going to have big issues!

NB: I'm not clear exaclty if yyyy-mm-dd is universally parsed in all cultures so maybe someone who knows can add a comment.

Try to use toISOString(). It returns string in ISO8601 format.

GET method

javascript

$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
    console.log(result);
});

c#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}

POST method

javascript

$.post('/example/do', { date: date.toISOString() }, function (result) {
    console.log(result);
});

c#

[HttpPost]
public JsonResult Do(DateTime date)
{
     return Json(date.ToString());
}

I set the below config on my MVC4 and it works like a charm

<globalization uiCulture="auto" culture="auto" />

  public class DateTimeFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.RequestType == "GET")
        {

            foreach (var parameter in filterContext.ActionParameters)
            {
                var properties = parameter.Value.GetType().GetProperties();

                foreach (var property in properties)
                {
                    Type type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;

                    if (property.PropertyType == typeof(System.DateTime) || property.PropertyType == typeof(DateTime?))
                    {
                        DateTime dateTime;

                        if (DateTime.TryParse(filterContext.HttpContext.Request.QueryString[property.Name], CultureInfo.CurrentUICulture, DateTimeStyles.None, out dateTime))
                            property.SetValue(parameter.Value, dateTime,null);
                    }
                }

            }
        }
    }
}

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var str = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
    if (string.IsNullOrEmpty(str)) return null;
    var date = DateTime.ParseExact(str, "dd.MM.yyyy", null);
    return date;
}

I set CurrentCulture and CurrentUICulture my custom base controller

    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);

        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-GB");
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");
    }

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 具有错误日期格式的MVC DateTime绑定(MVC DateTime binding with incorrect date format)
    问题 Asp.net-MVC现在允许DateTime对象的隐式绑定。 我采取了以下行动 public ActionResult DoSomething(DateTime startDate) { ... } 这成功地将一个字符串从ajax调用转换为DateTime。 但是,我们使用日期格式dd / MM / yyyy; MVC正在转换为MM / dd / yyyy。 例如,使用字符串'09 / 02/2009'提交对操作的调用会导致DateTime为'02 / 09/2009 00:00:00',或者在我们的本地设置中为9月2日。 我不想为了日期格式而滚动自己的模型活页夹。 但是似乎不需要更改操作以接受字符串,然后如果MVC能够为我执行此操作,则可以使用DateTime.Parse。 有什么方法可以更改DateTime的默认模型联编程序中使用的日期格式? 默认模型联编程序是否不应该使用您的本地化设置? 回答1 我刚刚通过更详尽的谷歌搜索找到了答案: 梅尔文·哈伯(Melvyn Harbor)全面解释了为什么MVC会以这种方式使用日期,以及在必要时如何覆盖日期: http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx 在寻找要解析的值时
  • ASP.NET MVC JsonResult日期格式(ASP.NET MVC JsonResult Date Format)
    问题 我有一个控制器操作,可以有效地简单返回模型的JsonResult。 因此,在我的方法中,我有以下内容: return new JsonResult(myModel); 除一个问题外,此方法运行良好。 模型中有一个date属性,它似乎在Json结果中返回,如下所示: "\/Date(1239018869048)\/" 我应该如何处理日期,以便它们以我需要的格式返回? 或者如何在脚本中处理上面的这种格式? 回答1 只是为了扩展casperOne的答案。 JSON规范不考虑Date值。 MS必须打个电话,他们选择的路径是利用字符串的javascript表示形式中的一个小技巧:字符串文字“ /”与“ \ /”相同,并且字符串文字永远不会序列化为“ \ /”(即使“ \ /”也必须映射到“ \\ /”)。 有关更好的说明,请参见http://msdn.microsoft.com/zh-cn/library/bb299886.aspx#intro_to_json_topic2(向下滚动到“从JavaScript文字到JSON”) JSON的痛处之一是缺少日期/时间文字。 许多人在初次遇到JSON时会感到惊讶和失望。 对于缺少日期/时间文字的简单解释(是否可以安慰)是JavaScript从来没有过:在JavaScript中对日期和时间值的支持完全通过Date对象提供。 因此
  • MVC custom validation: compare two dates
    I've created a custom ValidationAttribute that compares 2 dates and makes sure that the second date is greater than the first: public sealed class IsDateAfter : ValidationAttribute, IClientValidatable { private readonly string testedPropertyName; private readonly bool allowEqualDates; public IsDateAfter(string testedPropertyName, bool allowEqualDates = false) { this.testedPropertyName = testedPropertyName; this.allowEqualDates = allowEqualDates; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var propertyTestedInfo = validationContext
  • 如何在PHP中将日期转换为时间戳?(How to convert date to timestamp in PHP?)
    问题 我如何从22-09-2008获得时间戳? 回答1 这种方法适用于Windows和Unix平台,是时区意识到,这可能是你想要什么,如果你使用日期工作。 如果您不关心时区,或者想使用服务器使用的时区,请执行以下操作: $d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00'); if ($d === false) { die("Incorrect date string"); } else { echo $d->getTimestamp(); } 1222093324 (这取决于您的服务器时区...) 如果要指定在哪个时区,请在此处EST。 (与纽约相同。) $d = DateTime::createFromFormat( 'd-m-Y H:i:s', '22-09-2008 00:00:00', new DateTimeZone('EST') ); if ($d === false) { die("Incorrect date string"); } else { echo $d->getTimestamp(); } 1222093305 或者,如果您想使用UTC。 (与“ GMT”相同。) $d = DateTime::createFromFormat( 'd-m-Y H:i:s', '22-09
  • 如何验证python中的日期字符串格式?(How do I validate a date string format in python?)
    问题 我有一个python方法,它接受日期输入作为字符串。 如何添加验证以确保传递给方法的日期字符串在ffg中。 格式: 'YYYY-MM-DD' 如果不是,方法应该引发某种错误 回答1 >>> import datetime >>> def validate(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") >>> validate('2003-12-23') >>> validate('2003-12-32') Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> validate('2003-12-32') File "<pyshell#18>", line 5, in validate raise ValueError("Incorrect data format, should be YYYY-MM-DD") ValueError: Incorrect data format, should be YYYY-MM-DD 回答2
  • Format datetime in asp.net mvc 4
    How can I force the format of datetime in asp.net mvc 4 ? In display mode it shows as I want but in edit model it doesn't. I am using displayfor and editorfor and applyformatineditmode=true with dataformatstring="{0:dd/MM/yyyy}" What I have tried: globalization in web.config (both of them) with my culture and uiculture. modifying the culture and uiculture in application_start() custom modelbinder for datetime I have no idea how to force it and I need to input the date as dd/MM/yyyy not the default. MORE INFO: my viewmodel is like this [DisplayName("date of birth")] [DataType(DataType.Date)]
  • MVC DateTime validation - UK Date format
    I have a simple view with two date fields with ValidationMessageFor controls added for the unobtrusive JavaScript validation. My issue is I keep getting told my date is invalid, when it is in correct format (dd/MM/yyyy) I have added <globalization culture="en-GB" uiCulture="en-GB"/> to my web.config, and also included [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] on each DateTime property, yet it still won't accept UK format dates. Is there anything obvious I am missing here?
  • MVC4 DataType.Date EditorFor将不会在Chrome中显示日期值,但在Internet Explorer中很好(MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer)
    问题 我在模型上使用DataType.Date属性,并在视图中使用EditorFor。 在Internet Explorer 8和Internet Explorer 9中,这可以正常工作,但是在Google Chrome中,它显示的是日期选择器,而不是显示值,而只是以淡灰色文本显示“月/日/年”。 Google Chrome为什么不显示该值? 模型: [DataType(DataType.Date)] public Nullable<System.DateTime> EstPurchaseDate { get; set; } 看法: <td class="fieldLabel">Est. Pur. Date</td> <td class="field">@Html.EditorFor(m=>m.EstPurchaseDate)</td> 回答1 当使用[DataType(DataType.Date)]装饰模型属性时,ASP.NET MVC 4中的默认模板将生成type="date"的输入字段: <input class="text-box single-line" data-val="true" data-val-date="The field EstPurchaseDate must be a date." id="EstPurchaseDate" name=
  • MVC 4 date culture issue?
    I am using MVC 4 and am wondering if there is a bug in the Datetime culture info? I am trying to get Australian dates to work (dd/MM/yyyy), but it keeps saying that the date format is wrong, even after puttig a globalizaton to the web.config. I thought it was an error with my code, but even if you start a new project it still happens. I started a new MVC 4 Web application. Added the following to the web.config file <globalization culture="en-AU" uiCulture="en-AU" /> Then I added the following to the AccountModels.cs file: [DataType(DataType.DateTime)] [Required(ErrorMessage="Date is required")
  • Using DateTime in a SqlParameter for Stored Procedure, format error
    I'm trying to call a stored procedure (on a SQL 2005 server) from C#, .NET 2.0 using DateTime as a value to a SqlParameter. The SQL type in the stored procedure is 'datetime'. Executing the sproc from SQL Management Studio works fine. But everytime I call it from C# I get an error about the date format. When I run SQL Profiler to watch the calls, I then copy paste the exec call to see what's going on. These are my observations and notes about what I've attempted: 1) If I pass the DateTime in directly as a DateTime or converted to SqlDateTime, the field is surrounding by a PAIR of single quotes
  • The request sent by the client was syntactically incorrect.-Spring MVC + JDBC Template
    I am newbie to Spring MVC. I was stuck by an error while running my project Error-The request sent by the client was syntactically incorrect. I have an entity class PatientInfo. My jsp page is demo1. My controller is Patient Controller. The functionality i want to implement is Inserting values into database. But i am not able to call my function(add-update2) in controller. demo1.jsp <%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <html> <head> <title>Registration Form</title> </head> <body> <h2 align="center">Full Registration Form</h2> <hr /> <table align="center"
  • jquery ui datepicker and mvc view model type datetime
    I am using jquery datepicker on my view model Here is my view: @Html.TextBoxFor(o => o.JobStartDate, new { id = "dt1", @class = "input-block-level" }) @Html.ValidationMessage("JobStartDate") and my script: $("#dt1").datepicker({ dateFormat: "dd/mm/yy" }); Everything works fine if my date is <= 12, if my date is over 12, it will show me an validation error message saying "The field Start Date must be a date." (I am using jquery validation) For example: date 16/12/2014 will give me the error while 12/12/2014 won't Here is my view model: [Required] [DataType(DataType.Date)] [Display(Name = "Start
  • Display DateTime value in dd/mm/yyyy format in Asp.NET MVC
    Is it possible to display a DateTime value in dd/mm/yyyy format with the help of HTML Helper methods in Asp.NET MVC? I tried to do this by using some formats in @Html.LabelFor and adding some annotations to the related property like below but it does not make any sense. Any help to solve this problem would be appreciated. Model: [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public Nullable<System.DateTime> RegistrationDate { get; set; }
  • 使用Json.Net以dd / mm / yyyy格式反序列化日期(Deserializing dates with dd/MM/yyyy format using Json.Net)
    问题 我试图将对象从JSON数据反序列化为C#类(我使用的是Newtonsoft Json.NET)。 数据包含日期,例如字符串值,如09/12/2013 ,格式为dd/MM/yyyy 。 如果我调用JsonConvert.DeserializeObject<MyObject>(data) ,则将DateTime以MM/dd/yyyy格式加载到C#类的DateTime属性中,这将导致日期值为12 September 2013 9 December 2013 12 September 2013 (而不是12 September 2013 9 December 2013 ) 。 是否可以将JsonConvert配置JsonConvert以正确的格式获取日期? 回答1 您可以使用IsoDateTimeConverter并指定DateTimeFormat以获取所需的结果,例如: MyObject obj = JsonConvert.DeserializeObject<MyObject>(jsonString, new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" }); 演示: class Program { static void Main(string[] args) { string json = @"{ ""Date""
  • jQuery UI Datepicker和MVC视图模型类型datetime(jquery ui datepicker and mvc view model type datetime)
    问题 我在视图模型上使用jQuery Datepicker 这是我的看法: @Html.TextBoxFor(o => o.JobStartDate, new { id = "dt1", @class = "input-block-level" }) @Html.ValidationMessage("JobStartDate") 和我的脚本: $("#dt1").datepicker({ dateFormat: "dd/mm/yy" }); 如果我的日期小于等于12,一切正常,如果我的日期大于12,它将显示一条验证错误消息,提示“字段开始日期必须是日期。” (我正在使用jquery验证) 例如:日期2014年12月12日会给我错误,而2014年12月12日则不会 这是我的视图模型: [Required] [DataType(DataType.Date)] [Display(Name = "Start Date")] public DateTime JobStartDate { get; set; } 我怀疑我的视图模型正在预期格式为mm / dd / yyyy的日期,而在我的日期选择器中我指定了dd / mm / yy,有没有办法告诉我的视图模型我期望dd / mm / yy格式,所以如果日期> = 12,则不会引发错误消息。 回答1
  • Custom DateTime model binder in Asp.net MVC
    I would like to write my own model binder for DateTime type. First of all I'd like to write a new attribute that I can attach to my model property like: [DateTimeFormat("d.M.yyyy")] public DateTime Birth { get; set,} This is the easy part. But the binder part is a bit more difficult. I would like to add a new model binder for type DateTime. I can either implement IModelBinder interface and write my own BindModel() method inherit from DefaultModelBinder and override BindModel() method My model has a property as seen above (Birth). So when the model tries to bind request data to this property
  • How to handle json DateTime returned from WCF Data Services (OData)
    I believe I am missing something obvious here. When I request a JSON response from an OData service I get a different result for the DateTime properties than I do when I request XML. I'll use the NerdDinner OData feed as an example. JSON: http://www.nerddinner.com/Services/OData.svc/Dinners(1)?$format=json "EventDate": "\/Date(1235764800000)\/" XML: http://www.nerddinner.com/Services/OData.svc/Dinners(1) <d:EventDate m:type="Edm.DateTime">2009-02-27T20:00:00</d:EventDate> When I do an alert(new Date(1235764800000)) I get this result: I also get a result of 8PM when I run the same query with
  • How to accept Date params in a GET request to Spring MVC Controller?
    I've a GET request that sends a date in YYYY-MM-DD format to a Spring Controller. The controller code is as follows: @RequestMapping(value="/fetch" , method=RequestMethod.GET) public @ResponseBody String fetchResult(@RequestParam("from") Date fromDate) { //Content goes here } The request is sent correctly as I'm checking with Firebug. I get the error: HTTP Status 400: The request sent by the client was syntactically incorrect. How can I make the controller accept this format of Date? Please help. What am I doing wrong?
  • 仅来自TextBoxFor()的日期(Date only from TextBoxFor())
    问题 我无法使用TextBoxFor <,>(表达式,htmlAttributes)将DateTime的唯一日期部分显示到文本框中。 该模型基于Linq2SQL,字段是SQL上的Entity模型中的DateTime。 失败的: <%= Html.TextBoxFor(model => model.dtArrivalDate, String.Format("{0:dd/MM/yyyy}", Model.dtArrivalDate))%> 该技巧似乎已被弃用,对象htmlAttribute中的任何字符串值都将被忽略。 失败的: [DisplayFormat( DataFormatString = "{0:dd/MM/yyyy}" )] public string dtArrivalDate { get; set; } 我想只在细节/编辑视图中存储和显示日期部分,而没有“ 00:00:00”部分。 回答1 [DisplayName("Start Date")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] public DateTime StartDate { get; set; } 然后: <%=Html.EditorFor(m => m.StartDate) %>
  • WebApi Json.NET custom date handling
    I have globally explicitly configured my MVC4 app to use the JSON.NET serializer . I know i have the choice of using the ISO standard dates or the old Microsoft date format when serializing dates. But how can i output my own custom dateTime format string ,like :"dd/MM/yyyy hh:mm". I could do this in MVC3 when plugging in Json.NET as the default serializer but cant seem to do it in MVC4 . So far in the application_start i have done : var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings; JsonSerializerSettings jSettings = new Newtonsoft.Json