【问题标题】:Format datetime in asp.net mvc 4在asp.net mvc 4中格式化日期时间
【发布时间】:2012-07-01 15:19:08
【问题描述】:

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

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

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

更多信息: 我的视图模型是这样的

    [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)。

自定义模型绑定器在 application_start() 中调用 b/c 我不知道还有哪里。

使用<globalization/> 我尝试过使用culture="ro-RO", uiCulture="ro" 和其他可以给我dd/MM/yyyy 的文化。 我还尝试在 application_start() 中基于每个线程设置它(这里有很多示例,说明如何执行此操作)


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

【问题讨论】:

  • 您能提供更多信息吗?你的模型、控制器和视图?还提供一个示例,说明您在显示和编辑器模板之间获得的不同输出。另请注意,文化是按线程设置的。您提到了一些关于 Application_Start 的内容,但这只在您的应用程序启动时执行一次。后续请求呢?您如何为他们设置文化?
  • application_start 只执行一次!请改用 application_beginRequest!
  • Nas,application_beginRequest 在哪里?我只在 Global 中看到 application_start。在 mvc 4 中,事情开始与 mvc 3 有所不同

标签: asp.net-mvc asp.net-mvc-4 datetime-format


【解决方案1】:

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


显然有些问题仍然存在。这是我在 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());

还有自定义模型绑定器本身:

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;globalization&gt; 元素)或当前线程文化中设置了什么文化,自定义模型绑定器在解析可空日期时都将使用 DisplayFormat 属性的日期格式。

【讨论】:

  • 这是我用过的,但没有运气。我已经用日期时间和日期时间注册了它?它甚至没有显示我的错误消息,所以我认为它没有被使用。
  • 那我猜你必须展示你的完整代码让我们重现问题,因为我使用这个模型绑定器没有任何问题。
  • 出于好奇,它是什么类型的 MVC 项目(4 或 3)?
  • 经过测试并在 ASP.NET MVC 3 和 4 RC 上工作。我已经用我的完整工作示例更新了我的答案。所以现在问题变成了:您的设置与我的设置有何不同,您能否提供一个完整的示例(就像我所做的那样),以便我们重现您遇到的问题。否则我看不出我还能如何帮助你。
  • 我已经测试了您的示例并且它正在工作。有趣的是,在我的完整应用程序中,它仍然无法绑定。我从您那里得到的额外信息是视图中的@helper,因此我可以轻松插入字段。我将不得不重新创建整个应用程序,看看它从哪里开始失败。但除此之外(就我而言)您的自定义模型绑定器是完美的。
【解决方案2】:

由于 jquery.validate.unobtrusive.min.js 中的 MVC 错误(即使在 MVC 5 中),可能会出现客户端验证问题,该错误不接受任何日期/日期时间格式。不幸的是,您必须手动解决它。

我的最终解决方案:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

之前必须包含:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

您可以使用以下方式安装 moment.js:

Install-Package Moment.js

【讨论】:

    【解决方案3】:

    谢谢达林, 对我来说,为了能够发布到 create 方法,它只有在我将 BindModel 代码修改为:

    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.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), 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);
    }
    

    希望这可以帮助其他人......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      相关资源
      最近更新 更多