asp.net-mvc 绑定日期格式 (ASP.NET MVC)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/133671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 22:45:57  来源:igfitidea点击:

Format Date On Binding (ASP.NET MVC)

asp.net-mvc

提问by Corin Blaikie

In my ASP.net MVC app I have a view that looks like this:

在我的 ASP.net MVC 应用程序中,我有一个如下所示的视图:

...
<label>Due Date</label>
<%=Html.TextBox("due")%>
...

I am using a ModelBinderto bind the post to my model (the due property is of DateTimetype). The problem is when I put "01/01/2009" into the textbox, and the post does not validate (due to other data being input incorrectly). The binder repopulates it with the date and time"01/01/2009 00:00:00".

我正在使用 aModelBinder将帖子绑定到我的模型(due 属性是DateTime类型)。问题是当我将“01/01/2009”放入文本框时,帖子没有验证(由于其他数据输入不正确)。活页夹用日期和时间“01/01/2009 00:00:00”重新填充它。

Is there any way to tell the binder to format the date correctly (i.e. ToShortDateString())?

有没有办法告诉活页夹正确格式化日期(即ToShortDateString())?

回答by Nick Chadwick

I just came across this very simple and elegant solution, available in MVC 2:

我刚刚遇到了这个非常简单而优雅的解决方案,可在 MVC 2 中使用:

http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx

http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx

Basically if you are using MVC 2.0, use the following in your view.

基本上,如果您使用的是 MVC 2.0,请在您的视图中使用以下内容。

 <%=Html.LabelFor(m => m.due) %>
 <%=Html.EditorFor(m => m.due)%>

then create a partial view in /Views/Shared/EditorTemplates, called DateTime.ascx

然后在 /Views/Shared/EditorTemplates 中创建一个局部视图,名为 DateTime.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%=Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" }) %>

When the EditorFor<> is called it will find a matching Editor Template.

当 EditorFor<> 被调用时,它将找到一个匹配的编辑器模板。

回答by Qerim Shahini

Decorate the property in your model with the DataTypeattribute, and specify that its a Date, and not a DateTime:

用属性装饰模型中的DataType属性,并指定它的 a Date,而不是 a DateTime

public class Model {
  [DataType(DataType.Date)]
  public DateTime? Due { get; set; }
}

You do have to use EditorForinstead of TextBoxForin the view as well:

您也必须在视图中使用EditorFor而不是TextBoxFor

@Html.EditorFor(m => m.Due)

回答by Cephas

It's a dirty hack, but it seems to work.

这是一个肮脏的黑客,但它似乎有效。

<%= Html.TextBoxFor(model => model.SomeDate,
    new Dictionary<string, object> { { "Value", Model.SomeDate.ToShortDateString() } })%>

You get the model binding, and are able to override the HTML "value" property of the text field with a formatted string.

您获得模型绑定,并且能够使用格式化字符串覆盖文本字段的 HTML“值”属性。

回答by Casper

Why don't you use

你为什么不使用

<% =Html.TextBox("due", Model.due.ToShortDateString()) %>

回答by Craig M

I found this question while searching for the answer myself. The solutions above did not work for me because my DateTime is nullable. Here's how I solved it with support for nullable DateTime objects.

我在自己寻找答案时发现了这个问题。上面的解决方案对我不起作用,因为我的 DateTime 可以为空。这是我通过支持可为空的 DateTime 对象来解决它的方法。

<%= Html.TextBox(String.Format("{0:d}", Model.Property)) %>

回答by Serhiy

First, add this extension for getting property path:

首先,添加此扩展以获取属性路径:

public static class ExpressionParseHelper
{
    public static string GetPropertyPath<TEntity, TProperty>(Expression<Func<TEntity, TProperty>> property)
    {                       
         Match match = Regex.Match(property.ToString(), @"^[^\.]+\.([^\(\)]+)$");
         return match.Groups[1].Value;
    }
}

Than add this extension for HtmlHelper:

为 HtmlHelper 添加此扩展:

 public static MvcHtmlString DateBoxFor<TEntity>(
                this HtmlHelper helper,
                TEntity model,
                Expression<Func<TEntity, DateTime?>> property,
                object htmlAttributes)
            {
                DateTime? date = property.Compile().Invoke(model);
                var value = date.HasValue ? date.Value.ToShortDateString() : string.Empty;
                var name = ExpressionParseHelper.GetPropertyPath(property);

                return helper.TextBox(name, value, htmlAttributes);
            }

Also you should add this jQuery code:

您还应该添加此 jQuery 代码:

$(function() {
    $("input.datebox").datepicker();
});

datepicker is a jQuery plugin.

datepicker 是一个 jQuery 插件。

And now you can use it:

现在你可以使用它:

<%= Html.DateBoxFor(Model, (x => x.Entity.SomeDate), new { @class = "datebox" }) %>

ASP.NET MVC2 and DateTime Format

ASP.NET MVC2 和日期时间格式

回答by Ollie

I find the best way to do this is to reset the ModelValue

我发现最好的方法是重置 ModelValue

ModelState.SetModelValue("due", new ValueProviderResult(
       due.ToShortDateString(), 
       due.ToShortDateString(), 
       null));

回答by Switters

In order to get strongly typed access to your model in the code behind of your view you can do this:

为了在视图背后的代码中对模型进行强类型访问,您可以执行以下操作:

public partial class SomethingView : ViewPage<T>
{
}

Where T is the ViewData type that you want to pass in from your Action.

其中 T 是您要从 Action 传入的 ViewData 类型。

Then in your controller you would have an action :

然后在你的控制器中你会有一个动作:

public ActionResult Something(){
    T myObject = new T();
    T.Property = DateTime.Today();

    Return View("Something", myObject);
}

After that you have nice strongly typed model data in your view so you can do :

之后,您的视图中有很好的强类型模型数据,因此您可以执行以下操作:

<label>My Property</label>
<%=Html.TextBox(ViewData.Model.Property.ToShortDateString())%>

回答by Switters

I guess personally I'd say its best or easiest to do it via a strongly typed page and some defined model class but if you want it to be something that lives in the binder I would do it this way:

我想我个人会说最好或最简单的方法是通过强类型页面和一些定义的模型类来完成,但如果你希望它成为活页夹中的东西,我会这样做:

public class SomeTypeBinder : IModelBinder
{
    public object GetValue(ControllerContext controllerContext, string modelName,
                              Type modelType, ModelStateDictionary modelState)
    {
        SomeType temp = new SomeType();
        //assign values normally
        //If an error then add formatted date to ViewState
        controllerContext.Controller.ViewData.Add("FormattedDate",
                              temp.Date.ToShortDateString());
    }
}

And then use that in the view when creating the textbox i.e. :

然后在创建文本框时在视图中使用它,即:

<%= Html.TextBox("FormattedDate") %>

Hope that helps.

希望有帮助。

回答by RayLoveless

This worked for me: mvc 2

这对我有用:mvc 2

<%: Html.TextBoxFor(m => m.myDate, new { @value = Model.myDate.ToShortDateString()}) %>

<%: Html.TextBoxFor(m => m.myDate, new { @value = Model.myDate.ToShortDateString()}) %>

Simple and sweet!

简单又甜蜜!

A comment of user82646, thought I'd make it more visible.

user82646 的评论,以为我会让它更显眼。