【问题标题】:Create an Editor Template for DateTime with three input fields for day, month, year, in MVC在 MVC 中为 DateTime 创建一个编辑器模板,其中包含日、月、年的三个输入字段
【发布时间】:2012-08-04 00:06:53
【问题描述】:

我想为 DateTime 创建一个编辑器模板?具有日、月、年 3 个文本框的字段。目前我的 EditorTemplates/Date.cshtml 看起来像这样:

@Html.TextBox(string.Empty, Model.HasValue ? Model.Value.Day.ToString() : "",
                            new { @class = "day-box", title = "day", min = "1", max = "31", type = "number" })
@Html.TextBox(string.Empty, Model.HasValue ? Model.Value.Month.ToString() : "",
                            new { @class = "month-box", title = "month", min = "1", max = "12", type = "number" })
@Html.TextBox(string.Empty, Model.HasValue ? Model.Value.Year.ToString() : "",
                    new { @class = "year-box", title = "year", min = "1900", max = "2020", type = "number" })

明显的问题是(原样) id 和 name 属性都设置为相同的值。我需要在这些值上附加一些东西,并且永远不要让它回到我的模型中。

我希望将 _Day 附加到 id,并将 .Day 附加到 Day 输入的名称,同样的月份和年份可以解决问题。但我看不到这样做的简单方法。

我打算使用隐藏输入作为实际值,然后每次在我的三个 (d/m/y) 文本框之一中的值发生变化时使用 javascript 更新隐藏字段的值。

那么当我传入 string.Empty 时,有没有办法获取 MVC 将要使用的名称和 ID?使用 ViewData.TemplateInfo.HtmlPrefix 似乎没有提供全部价值。

有没有更好的方法来做我想做的事?我无法想象我是第一个解决这个问题的人。

我知道那里有第 3 方日期选择器。为了这个问题,我对它们不感兴趣。

谢谢, ~S

【问题讨论】:

  • 手动编写 标签怎么样?还是简单地为日、月和年创建 c# 属性?

标签: c# asp.net-mvc asp.net-mvc-3 datetime datetimepicker


【解决方案1】:

如果 DateTime 的年月日可设置,您可以在 DateTime.cshtml EditorTemplates 上执行此操作

@model System.DateTime
@Html.TextBoxFor(model => model.Year) / @Html.TextBoxFor(model => model.Month) / @Html.TextBoxFor(model => model.Day)

以上是不可能的。 DateTime 的年、月和日属性是只读的。

你可以做的就是创建一个单独的数据类型:

public struct DatePart
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }

    public DateTime Date { get { return new DateTime(Year, Month, Day); } }
}

然后在您的日期编辑器模板上执行此操作

@model TestV.Models.DatePart           
@Html.TextBoxFor(model => model.Year) / @Html.TextBoxFor(model => model.Month) / @Html.TextBoxFor(model => model.Day)

然后只需访问 DatePart 的 Date(DateTime 类型) 属性

【讨论】:

    【解决方案2】:

    您可以使用 javascript 从自定义模板中的三个字段形成日期,并将其写入将绑定到您的 Model.Date 的隐藏字段中

    【讨论】:

      猜你喜欢
      • 2011-10-05
      • 2019-10-24
      • 2018-12-11
      • 1970-01-01
      • 2015-09-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      相关资源
      最近更新 更多