1

使用MVC 4& 我创建了一个编辑器模板,以仅显示来自对象的HH:mm格式时间DateTime

编辑器模板代码 (TimePicker.cshtml)

@model DateTime?
@{
    String modelValue = "";
    var dateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
    var id = "";
    var cls = "";
    var style = "";
    var placeholder = "";

    if (ViewData["_id"] != null)
    {
        id = (string)ViewData["_id"];
    }
    if (ViewData["_class"] != null)
    {
        cls = (string)ViewData["_class"];
    }
    if (ViewData["_style"] != null)
    {
        style = (string)ViewData["_style"];
    }
    if (ViewData["_placeholder"] != null)
    {
        placeholder = (string)ViewData["_placeholder"];
    }

    if (Model.HasValue)
    {
        if (Model.Value != DateTime.MinValue)
        {
            modelValue = Model.Value.ToString("HH:mm", dateFormat);
        }
    }
}
@Html.TextBox("", modelValue, 
           new { @class = cls, @id = id, @style = style, @placeholder = placeholder })

在视图中

 @Html.EditorFor(m => m.StartTime, "TimePicker", new { _id = "StartTime"})

但最终呈现的 HTML 是

 <input id="StartTime" name="StartTime" type="text" value="2013-08-05 0:00:00" />

即使我尝试对调试值进行硬编码,如下所示

@Html.TextBox("", "00:00", 
           new { @class = cls, @id = id, @style = style, @placeholder = placeholder })

我仍然得到相同2013-08-05 0:00:00的而不是0:00

代码中的问题是什么?

编辑:在快速观察adding name parameter到 TextBox 给出一个结果。但它附加了名称属性,这是我不想要的。找到这个截图 在此处输入图像描述

4

1 回答 1

3

在阅读了这个MVC 3 - Html.EditorFor 似乎在 $.ajax 调用之后缓存旧值之后,我意识到在绑定之前,HtmlHelper 会查看ModelState.

不确定检查 ModelState 的意图/好处是什么,而不是绑定所提供的任何值。

但是,在设置值之前,我在控制器中添加了此代码。现在它工作正常。

 ModelState.Remove("StartTime"); 
 ModelState.Remove("EndTime");

 bookingViewModel.StartTime = Convert.ToDateTime(startTime);
 bookingViewModel.EndTime = Convert.ToDateTime(endTime);

 return View("Booking", bookingViewModel);
于 2013-08-24T09:31:56.610 回答