如何使用输入类型=日期的 Html.TextBoxFor? [英] How to use Html.TextBoxFor with input type=date?

查看:24
本文介绍了如何使用输入类型=日期的 Html.TextBoxFor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的代码中实现.为此,我有以下几点:

I want to implement in my code. To that end, I have the following:

@Html.TextBoxFor(model => model.CreationDate, new { @type = "date" })

此代码生成以下 HTML:

This code generates the following HTML:

<input data-val="true" data-val-date="The field CreationDate must be a date." 
             data-val-required="The CreationDate field is required." 
             id="CreationDate" name="CreationDate" type="date" 
             value="09/05/2012 15:02:19">

该值未显示在网页上,因为 type="date" 需要 YYYY-MM-DD 格式的数据.

The value does not show up on the web page because type="date" expects data in YYYY-MM-DD format.

我试过格式化日期,但当然失败了.

I've tried formatting the date, but that blows up, of course.

@Html.TextBoxFor(model => model.CreationDate.ToString("YYYY-MM-DD"), 
                 new { @type = "date" })

如何使用 TextBoxFor 方法正确显示构造?或者我应该使用其他方法(我已经尝试过 EditorFor 但失败了)?

How do I use TextBoxFor method to properly display the construct? Or should I be using some other method (I already tried EditorFor but failed)?

CreationDate 是 DateTime 类型.

CreationDate is of type DateTime.

推荐答案

试试这个;

@Html.TextBoxFor(model => model.CreationDate,
           new { @type = "date", @Value = Model.CreationDate.ToString("yyyy-MM-dd") })

设置值时必须处理null.

如果你可以改变Model你可以试试这个;

If you can change the Model you can try this;

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

在您看来,您可以使用 EditorFor 助手.

and in your view you can use EditorFor helper.

@Html.EditorFor(model => model.CreationDate, new { @type = "date" })

这篇关于如何使用输入类型=日期的 Html.TextBoxFor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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