在 asp.net mvc 4 中格式化日期时间 [英] Format datetime in asp.net mvc 4

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

问题描述

如何在 asp.net mvc 4 中强制使用日期时间格式?在显示模式下,它按我的意愿显示,但在编辑模型中却没有.我正在使用 displayfor 和 editorfor 以及 applyformatineditmode=true 和 dataformatstring="{0:dd/MM/yyyy}"我尝试过的:

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:

  • 使用我的文化和 uiculture 在 web.config(两者)中进行全球化.
  • 在 application_start() 中修改文化和用户文化
  • 日期时间的自定义模型绑定器

我不知道如何强制它,我需要输入日期为 dd/MM/yyyy 而不是默认值.

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)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }

在视图中我使用 @Html.DisplayFor(m=>m.Birth) 但这按预期工作(我看到格式)并输入日期我使用 @Html.EditorFor(m=>m.Birth) 但如果我尝试输入类似 13/12/2000 的内容失败,错误是它不是有效日期(12/13/2000 和 2000/12/13 按预期工作,但我需要 dd/MM/yyyy).

in view I use @Html.DisplayFor(m=>m.Birth) but this works as expected (I see the formatting) and to input the date I use @Html.EditorFor(m=>m.Birth) but if I try and input something like 13/12/2000 is fails with the error that it is not a valid date (12/13/2000 and 2000/12/13 are working as expected but I need dd/MM/yyyy).

自定义模型绑定器在 application_start() b/c 中调用,我不知道其他地方.

The custom modelbinder is called in application_start() b/c I don't know where else.

使用 <globalization/> 我已经尝试过 culture="ro-RO", uiCulture="ro" 和其他会给我 dd/的文化月/年.我还尝试在 application_start() 中基于每个线程设置它(这里有很多示例,关于如何执行此操作)

Using <globalization/> I have tried with culture="ro-RO", uiCulture="ro" and other cultures that would give me dd/MM/yyyy. I have also tried to set it on a per thread basis in application_start() (there are a lot of examples here, on how to do this)

对于所有会阅读这个问题的人:只要我没有客户验证,Darin Dimitrov 的答案似乎就会起作用.另一种方法是使用自定义验证,包括客户端验证.我很高兴在重新创建整个应用程序之前发现了这一点.

For all that will read this question: It seems that Darin Dimitrov's answer will work as long as I don't have client validation. Another approach is to use custom validation including client side validation. I'm glad I found this out before recreating the entire application.

推荐答案

啊,现在清楚了.您似乎在绑定值时遇到问题.不是在视图上显示它.事实上,这是默认模型绑定器的错误.您可以编写和使用一个自定义的,它会考虑模型上的 [DisplayFormat] 属性.我在这里展示了这样一个自定义模型绑定器:https://stackoverflow.com/a/7836093/29407

Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat] attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407

显然有些问题仍然存在.这是我的完整设置,在 ASP.NET MVC 3 和 ASP.NET MVC 3 上都运行良好.4 RC.

Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.

型号:

public class MyViewModel
{
    [DisplayName("date of birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Birth = DateTime.Now
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

查看:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Birth)
    @Html.EditorFor(x => x.Birth)
    @Html.ValidationMessageFor(x => x.Birth)
    <button type="submit">OK</button>
}

Application_Start 中注册自定义模型绑定器:

Registration of the custom model binder in Application_Start:

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

以及自定义模型绑定器本身:

And the custom model binder itself:

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);
    }
}

现在,无论您在 web.config(<globalization> 元素)中设置什么文化或当前线程文化,自定义模型绑定器都将使用 DisplayFormat 属性在解析可为空日期时的日期格式.

Now, no matter what culture you have setup in your web.config (<globalization> element) or the current thread culture, the custom model binder will use the DisplayFormat attribute's date format when parsing nullable dates.

这篇关于在 asp.net mvc 4 中格式化日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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