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

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

问题描述

我怎么可以强制日期时间在asp.net mvc的4格式?
在显示模式下,它显示了,因为我想但在编辑模式没有。
我使用displayfor和editorfor和applyformatineditmode =真与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:


  • 全球化在web.config中(两者),与我的Culture和UICulture。

  • 修改的区域性和uiculture中的Application_Start()

  • 对日期时间定制ModelBinder的

我不知道如何给力了,我需要输入日期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 = GT; m.Birth)但这按预期工作(我看到了格式化)
并输入我使用的日期 @ Html.EditorFor(M = GT; m.Birth)但如果我尝试输入类似13/12/2000是失败的错误,这不是(2000年12月13日和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.

使用<全球化/> 我曾尝试与文化=RO-RO的UICulture =RO和其他文化,这将使我的DD / MM / YYYY。
我也曾尝试将其设置在每个线程的基础在的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)

对于所有将读取这个问题:
看来,达林季米特洛夫的回答会只要我没有客户端验证工作。
另一种方法是使用自定义的验证,包括客户端验证。
我很高兴我重新创建整个应用程序之前发现这一点。

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] 属性。我在这里说明这样一个自定义的模型绑定: http://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: http://stackoverflow.com/a/7836093/29407

显然,一些问题依然存在。这里是我的全部设置工作完全正常两个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

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(&LT;全球化&GT; 元素)或当前线程文化,自定义模型粘合剂将使用 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天全站免登陆