【问题标题】:Format TextBoxFor database first custom date formatFormat TextBoxFor 数据库第一个自定义日期格式
【发布时间】:2015-06-23 15:29:06
【问题描述】:

我正在使用 MVC4 并为在 SQL 服务器上驱动的大型进程构建前端应用程序 - 所以我的 EF 方法是首先使用数据库,因为所有逻辑和处理都在那里完成。

我有一个实体(Sql 表),它有一个日期字段,但它写为 Decimal(8, 0),格式为“yyyyMMdd”(20160623)。

有没有办法让我执行 DateTime.TryParseExact 并将 Datetime 值返回到 TextBoxFor? TryParseExact,因为值为 0、有效日期、99999999。

我尝试使用辅助方法(c# 不是 cshtml),但我得到了一个

模板只能用于字段访问、属性访问、单维数组索引或单参数自定义索引器表达式

我不想摆弄模型和 DisplayFormat 注释,因为我可以预期数据库会更改,并且从数据库更新模型会覆盖我的格式。

编辑:

这将是一个临时解决方案,但也许会有更好的方法(并且实际上使用 TextBoxFor)

@Html.TextBox("DateAdded", nHelpers.YYYYMMDDToShortDateString(Model.DateAdded.ToString), New With {.class = "tBox", .style = "width: 80px"})

【问题讨论】:

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


    【解决方案1】:

    Views\Shared\EditorTemplates,创建名为 CoreDateToShortDateString 的新局部视图。使用此代码:

    @ModelType System.Decimal?
    @If Model IsNot Nothing Then
      Dim datum As DateTime
      If DateTime.TryParseExact(Model.Value.ToString, "yyyyMMdd", Nothing, Globalization.DateTimeStyles.None, datum) Then
        @Html.TextBox("", datum.ToShortDateString)
      Else
        @Html.TextBox("", Model.Value)
      End If
    End If
    

    使用:

    @Html.EditorFor(Function(model) model.DateAdded, "CoreDateToShortDateString")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      相关资源
      最近更新 更多