MVC 4编辑模板为HH显示时间:mm格式 [英] MVC 4 Editor Template for Displaying Time in HH:mm Format

查看:154
本文介绍了MVC 4编辑模板为HH显示时间:mm格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MVC 4个工作日&安培;我创建了一个模板编辑器只显示在时间HH:MM 从格式的DateTime 对象

Working with MVC 4 & I created a Editor template to show only the time in HH:mm format from DateTime object

编辑模板code(TimePicker.cshtml)

Editor Template Code (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 })

在View

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

但是呈现最终的HTML是

But the Final HTML Rendered was

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

即使我试着硬编码以下

Even I tried hard coding the value for debugging like below

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

我仍然得到同样的 2013年8月5日0:00:00 而不是 0:00

什么是在code中的问题?

What is the problem in the code?

修改:在快速监视添加名称参数来的TextBox给出一个结果。但它与name属性,这我不希望它追加。找到这个截图

EDIT: In Quick watch adding name parameter to TextBox gives a result. But it appends it with name attribute, which i dont want. Find this screenshot

推荐答案

看完这个<一个href=\"http://stackoverflow.com/questions/7414351/mvc-3-html-editorfor-seems-to-cache-old-values-after-ajax-call\">MVC 3 - Html.EditorFor似乎后$就调用缓存旧的价值观,我意识到绑定之前,将的HtmlHelper看看的ModelState

After reading this MVC 3 - Html.EditorFor seems to cache old values after $.ajax call , I realized that before binding, HtmlHelper will look into ModelState.

不知道什么是检查ModelState中,而不是结合以往的价值提供什么样的意图/效益。

不过,我在我的控制器设置值之前,增加此code。现在,它工作正常。

However I added this code in my controller before setting the value. Now it works fine.

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

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

 return View("Booking", bookingViewModel);

这篇关于MVC 4编辑模板为HH显示时间:mm格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆