【问题标题】:DateTime field and Html.TextBoxFor() helper. How to use it correctly?DateTime 字段和 Html.TextBoxFor() 助手。如何正确使用?
【发布时间】:2013-09-11 03:35:38
【问题描述】:

我的模型中有一个 DateTime 字段。如果我尝试以这种方式在强类型部分视图中使用此字段

<%= Html.TextBoxFor(model => model.DataUdienza.ToString("dd/MM/yyyy"), new { style = "width: 120px" })  %>

运行时会出现如下编译错误

System.InvalidOperationException : Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

无论如何,如果我使用它删除格式,ToString("dd/MM/yyyy"),一切正常,但该字段使用我根本不需要的时间部分进行格式化。 p>

我哪里做错了?处理这个问题的正确方法是什么?

感谢您的帮助!

编辑

这是模型类中的属性声明

[Required]
[DisplayName("Data Udienza")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DataUdienza { get; set; }

【问题讨论】:

    标签: asp.net-mvc html-helper


    【解决方案1】:

    我在 mvc 4 中使用它。它也可以工作~

    @Html.TextBoxFor(x => x.DatePurchase, "{0:yyyy-MM-dd}", new { @class = "dateInput", @placeholder = "plz input date" })
    

    【讨论】:

    • 感谢非常好的解决方案。但我真的需要看看为什么它没有使用网络配置中指定的设置的文化信息。
    【解决方案2】:
    <%= Html.EditorFor(model => model.DataUdienza) %>
    

    在你的模型中:

    [DisplayFormat(ApplyFormatInEditMode = true, 
                   DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime DataUdienza { get; set; }
    

    EditorFor 的缺点是您不能将自定义 html 属性应用于生成的字段。作为替代方案,您可以使用 TextBox 助手:

    <%= Html.TextBox("DataUdienza", Model.Date.ToString("dd/MM/yyyy"), new { style = "width: 120px" })%>
    

    【讨论】:

    • 哇!超级快。谢谢 :) 我要试试。但是,与此同时,如果该字段是 Nullable 类型,这将如何工作?
    • 对可空类型的工作方式相同。
    • 我已尝试应用您的解决方案,但不幸的是不起作用。我将编辑帖子以添加模型属性声明以供您参考。
    • @Lorenzo,您是否注意到应该使用Html.EditorFor 而不是Html.TextBoxFor
    • @Darin:我以前从未使用过 EditorFor。无论如何,请考虑现在添加了两个属性(DataType 和 DisplayFormat)来尝试您的建议。
    【解决方案3】:

    创建一个名为 DateTime.ascx 的编辑器模板

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
    <%=Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), ViewData) %>
    

    将它放在您的 Views/Shared/EditorTemplates 文件夹中。现在当你打电话时:

    <%= Html.EditorFor(model => model.DataUdienza) %>
    

    您的 DateTime 将被格式化,没有时间。

    这将发生在所有以这种方式调用的 DateTimes 上,不过...

    自定义html属性可以这样使用:

    <%= Html.EditorFor(model => model.DataUdienza, new {customAttr = "custom", @class = "class"}) %>
    

    它作为 ViewData 传递给 EditorTemplate。

    【讨论】:

      【解决方案4】:

      至少如果使用razor,你可以命名模板,所以你不需要为所有的DateTimes使用相同的模板:

      @Html.EditorFor(m => m.StartDate, "Date")
      

      其中 Date.cshtml 包含一个 TextBoxFor 或其他一些编辑器,就像@JungleFreak 解释的那样:

      @model DateTime?
      
      @Html.TextBox("", Model.HasValue ? Model.Value.ToShortDateString() : string.Empty, 
          new { data_datepicker = true })
      

      【讨论】:

        【解决方案5】:

        也许可以创建一个扩展方法:

            public static MvcHtmlString DateTimeFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
            {
                var compilationResult = expression.Compile();
                TValue dateValue = compilationResult((TModel)html.ViewDataContainer.ViewData.Model);
                var body = (MemberExpression)expression.Body;
                return html.TextBox(body.Member.Name, (Convert.ToDateTime(dateValue)).ToCustomDateFormat(), new { id = body.Member.Name, datepicker = true });
            }
        

        ToCustomDateFormat 方法可以是 dateTime 类型的扩展方法,它以所需格式返回字符串值。

        用法:

        @Html.DateTimeFor(x=>x.AnyDateTimeProperty)
        

        对我来说工作得很好(DateTimeDateTime? 属性),虽然我不确定在运行时编译表达式是否是个好主意。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多