日期格式dd/MM/yyyy在asp.net mvc 5中不起作用 [英] date format dd/MM/yyyy not working in asp.net mvc 5

查看:267
本文介绍了日期格式dd/MM/yyyy在asp.net mvc 5中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个asp.net mvc 5应用程序,在其中我试图为 dd/MM/yyyy 格式设置验证,但我一直在努力寻找一个适当的解决方案,但没有成功,我希望它接受什么:

I'm developing an asp.net mvc 5 application, in which I'm trying to set a validation for dd/MM/yyyy format, I've been struggling a lot to find an appropriate solution but no success, what I want it to accept:

24/01/2016

但是它将验证消息显示为:

but it displays validation message as :

JoiningDate字段必须为日期.

The field JoiningDate must be a date.

这是我尝试过的:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime JoiningDate { get; set; }

此外,我希望它在用户端的任何地方以 dd/MM/yyyy 格式显示日期,但这是我的问题的第二部分,首先,它至少应允许一个有效的日期.日期输入.我受困于此,任何帮助都会得到深深的赞赏,我已经四处搜寻,但是我无法直截了当地,谢谢您提前:)

Also, I want it to display the date in dd/MM/yyyy format everywhere at the user's end but this is a second part of my question, firstly, it should at least allow a valid date input. I'm stuck on this one, any help will be deeply appreciated, I've searched all over, but I'm not being able to get to the point, Thanks In Advance :)

推荐答案

我得到了答案,我使用了自定义ModelBinder,以解决此问题,

I got the answer, I used custom ModelBinder, in order to resolve this issue,

首先,我在Global.asax的application_start方法中注册了这一行:

Firstly, I registered this line in the application_start method in Global.asax:

ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());

这是自定义ModelBinder:

Here is the custom ModelBinder :

public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName,
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

感谢达林·迪米特洛夫(Darin Dimitrov)的答案

Thanks to Darin Dimitrov's answer!

这篇关于日期格式dd/MM/yyyy在asp.net mvc 5中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆