日期不会在HTML输入类型日期的Model中显示 [英] Date does not display from Model on HTML input type date

查看:150
本文介绍了日期不会在HTML输入类型日期的Model中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的创建和编辑Razor视图上显示日期类型输入...日期选择器工作正常,但是在编辑时我确实从模型中获取了值,但日期选择器未显示它...

I am trying to display a date type input on my create and edit Razor Views... The date picker works fine but when editing I do get the value from the Model but the date picker does not display it...

查看

<div class="form-group form-md-line-input">
    @Html.TextBoxFor(model => model.InitialDate, new { @class = "form-control", type = "date" })
    @Html.ValidationMessageFor(model => model.InitialDate)
    @Html.LabelFor(model => model.InitialDate)
</div>

模型

public Nullable<System.DateTime> InitialDate { get; set; }

我尝试使用DataAnnotations,但是同样的事情发生了,日期选择器仅允许我在创建时选择日期,但是在编辑时,它却无法显示模型中的日期,尽管当我查看HTML代码时呈现后,将设置日期值,但控件不会显示它.

I have tried using the DataAnnotations but the same thing happens the date picker only allows me to select the date on the create but when editing it does not display the date from the model although when I looked at the HTML Code that is rendered, the value for the date is being set but the control does not display it.

HTML视图

<input class="form-control" data-val="true" data-val-date="The field InitialDate must be a date." id="InitialDate" name="InitialDate" type="date" value="3/3/2015 12:00:00 AM">

我还从浏览器的开发人员工具的属性值中删除了时间,以查看它是否有效,但是它也不起作用...

I also removed the time from attribute value from the browser's developers tools to see if it works, but it didn't work either...

<input class="form-control" data-val="true" data-val-date="The field InitialDate must be a date." id="InitialDate" name="InitialDate" type="date" value="3/3/2015">

如何在日期选择器中显示模型中的日期?任何帮助将不胜感激...

How can I Display the Date from the Model in the date picker? Any help will be appreciated...

推荐答案

如果使用此代码生成浏览器HTML5 datepicker实现,则日期格式必须为yyyy-MM-dd(ISO格式).使用TextBoxFor()它必须是

If your using this to generate the browsers HTML5 datepicker implementation, the format of the date needs to be yyyy-MM-dd (ISO format). Using TextBoxFor() it needs to be

@Html.TextBoxFor(m => m.InitialDate, "{0:yyyy-MM-dd}", new { @class = "form-control", type = "date" })

或者,将以下属性添加到属性中

Alternatively, add the following attributes to the property

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> InitialDate { get; set; }

并在视图中使用

@Html.EditorFor(m => m.InitialDate)

请注意,这会添加type="date"属性

这篇关于日期不会在HTML输入类型日期的Model中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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