绑定时的格式化日期(ASP.NET MVC)

时间:2008-09-25 14:25:48

标签: asp.net-mvc

在我的ASP.net MVC应用程序中,我有一个看起来像这样的视图:

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

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

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

12 个答案:

答案 0 :(得分:55)

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

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

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

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

然后在/ 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" }) %>

当EditorFor&lt;&gt;被称为它将找到匹配的编辑模板。

答案 1 :(得分:24)

使用DataType属性装饰模型中的属性,并指定其为Date,而不是DateTime

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

您还必须在视图中使用EditorFor代替TextBoxFor

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

答案 2 :(得分:9)

这是一个肮脏的黑客,但它似乎工作。

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

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

答案 3 :(得分:4)

为什么不使用

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

答案 4 :(得分:4)

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

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

答案 5 :(得分:3)

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

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

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

此外,您应该添加此jQuery代码:

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

datepicker是一个jQuery插件。

现在你可以使用它了:

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

ASP.NET MVC2 and DateTime Format

答案 6 :(得分:1)

为了在视图后面的代码中获得对模型的强类型访问,您可以这样做:

public partial class SomethingView : ViewPage<T>
{
}

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

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

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

    Return View("Something", myObject);
}

之后,您在视图中拥有了很好的强类型模型数据,因此您可以这样做:

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

答案 7 :(得分:1)

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

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

答案 8 :(得分:0)

我个人认为我会通过强类型页面和一些已定义的模型类来说它是最好或最简单的,但如果你想让它成为粘合剂中的东西,我会这样做:

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

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

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

希望有所帮助。

答案 9 :(得分:0)

这对我有用:mvc 2

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

简单又甜蜜!

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

答案 10 :(得分:0)

试试这个

<%:Html.TextBoxFor(m => m.FromDate, new { @Value = (String.Format("{0:dd/MM/yyyy}", Model.FromDate)) }) %>

答案 11 :(得分:0)

MVC4 EF5 View我试图用今天的日期预加载一个字段,然后将其传递给视图进行审批。

ViewModel.SEnd = DateTime.Now    //preload todays date  
return View(ViewModel)           //pass to view

在视图中,我的第一个代码允许编辑:

@Html.EditedFor(item.SEnd)        //allow edit

后来我把它更改为只显示日期,用户无法更改它但提交触发控制器保存更改

 <td>
 @Html.DisplyFor(item.SEnd)       //show no edit
 </td>

当我更改为DisplayFor时,我需要添加它以确保将预加载的值传递回控制器。我还需要为viewmodel中的每个字段添加HiddenFor。

    @Html.HiddenFor(model => model.SEnd)     //preserve value for passback.

初学者的东西,但需要一段时间来解决这个问题。