0

我从 .NET MVC Web 应用程序中的 Action 的隐式绑定中获取 DateTime。问题是我正在获取格式为“MM/dd/yyyy”的日期,而我通过带有 Ajax 格式的查询字符串发送它,格式为“dd/MM/yyyy”。

我知道这是使用 GET 协议而不是 POST 时 .NET MVC Binder 的一个已知问题,所以我确实实现了一个自定义活页夹来将日期解析为正确的格式。这是代码:

public class SearchVMBinder:DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        SearchVM result = (SearchVM)base.BindModel(controllerContext, bindingContext);
        try
        {                
            result.Date = DateTime.Parse(result.Date.ToString(),CultureInfo.GetCultureInfo("es-ES"));
        }
        catch(Exception e)
        {
            NLog.LogManager.GetCurrentClassLogger().Error("Error al hacer el Bind específico de SearchVM. ", e);
        }

        return result;
    }
}

但是,使用该代码 Parse 无法正常工作,它什么也不做。我正在使用“01/04/2014 11:37:00”(四月)之类的日期对其进行测试,并且我正在“result.Date”日期“04/01/2014 11:37:00” (一月),在解析之前和之后。

所以,问题是:为什么“DateTime.Parse”方法不能正确解析日期?

更新:

下面是 SearchVM 的代码:

[ModelBinder(typeof(SearchVMBinder))]
public class SearchVM
{
    public DateTime Date { get; set; }
    public string StudyCaseNumber { get; set; }
    public string PatientNumber { get; set; }
    public string PatientName { get; set; }
    public string PatientFamilyName { get; set; }
    public string PatientMothersMaidenName { get; set; }
    public string DoctorName { get; set; }
    public string RoomName { get; set; }
    public E_OrderedBy OrderBy { get; set; }

}

这里是控制器动作的标题:

public ActionResult ListSearch(SearchVM searchFilter)

谢谢你。

4

4 回答 4

0

开始了:

尝试将您的 DateTime 作为 UTC 字符串发布/发送:您可以像这样转换:

DateTime startdate = TimeZoneInfo.ConvertTimeToUtc(input.startdate.Value);   //Converting to UTC time from local time

希望能帮助到你;)

于 2016-04-27T10:20:42.077 回答
0

您的代码正在运行。

请参阅此问题的最佳答案:将日期时间从英语转换为西班牙语

你说:

但是,使用该代码 Parse 无法正常工作,它什么也不做。我正在使用“01/04/2014 11:37:00”(四月)之类的日期对其进行测试,并且我正在“result.Date”日期“04/01/2014 11:37:00” (一月),在解析之前和之后。

这是一种非常特殊的不工作方式——这是由于语言环境不同而导致的。您使用了“es-ES”格式。

https://www.bjelic.net/2011/01/26/coding/formatting-date-time-currency-in-various-cultures/

result.Date = 

    DateTime.Parse(result.Date.ToString(),
    CultureInfo.GetCultureInfo("es-ES"));

结果日期是根据您的“01/04/2014 11:37:00”和es-ES区域设置是 dd/MM/yyyy,所以由于您当前使用的是英语,它会进行转换。

于 2016-04-27T10:28:10.010 回答
0

像这样的东西会起作用

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var testFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(testFormat) && value != null)
        {
            DateTime testDate;
            testFormat = testFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the testFormat attribute to parse the date
            if(DateTime.TryParseExact(value.AttemptedValue, testFormat, new System.Globalization.CultureInfo("es-ES"), DateTimeStyles.None, out testDate);)
            {
                return testDate;
            }
            else
            {
                //if you want allow nulls
                //date = DateTime.Now.Date;
                //return date;

                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName,
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
于 2016-04-27T10:21:15.103 回答
0

好的,由于某种原因,“Parse”方法没有正确解释传入的 DateTime 格式,即“MM/dd/yyyy H:mm:ss”,所以我不得不使用“ParseExact”方法来指定它。

现在,这非常适合西班牙文化信息:

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        SearchVM result = (SearchVM)base.BindModel(controllerContext, bindingContext);
        try
        {
            if (result != null)
            {
                if (result.NullableDate != null)
                {                                      
                    result.NullableDate = DateTime.ParseExact(result.NullableDate.ToString(), "MM'/'dd'/'yyyy H:mm:ss", new CultureInfo("es-ES"));
                }
            }

        }
        catch(Exception e)
        {
            NLog.LogManager.GetCurrentClassLogger().Error("Error al hacer el Bind específico de SearchVM. ", e);
        }

        return result;
    }
于 2016-05-09T09:40:54.417 回答