我的 ASP.NET MVC3 应用程序中有日期时间输入:
<div class="editor-field">
@Html.EditorFor(model => model.Article.PublishedDate)
@Html.ValidationMessageFor(model => model.Article.PublishedDate)
</div>
在 Opera 中,它对日期和时间进行特殊输入,但当我编辑模型时,它是空的,我想将其设置为值。在其他浏览器中,它是常规文本框并且设置了日期时间。感谢生成的代码是:
<input class="text-box single-line" data-val="true" data-val-required="Publish date is required" id="Article_PublishedDate" name="Article.PublishedDate" type="datetime" value="30.3.2012 10:00:00" data-default-value=""/>
如何修复它并在 Opera 中设置日期时间?
最佳答案
您需要根据RFC3339格式化您的日期时间标准
HTML5 输入日期时间规范:http://dev.w3.org/html5/markup/input.datetime.html
因此您的值需要采用如下格式:
<input ... type="datetime" value="2012-03-30T10:00:00" ... />
要将日期格式化为 RFC3339,您可以调用:
DateTime.ToString("yyyy-MM-ddThh:mm:ssZ");
您可以通过向 Article.PublishedDate 添加 DisplayFormatAttribute 来实现此目的:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-ddThh:mm:ssZ}")]
public DateTime PublishedDate { get; set; }
现在的问题(至少对我来说)是该属性现在始终保持这样的格式。您可以为此使用 EditorFor 模板:
@model DateTime?
@{
var attributes = new Dictionary<string, object>();
attributes.Add("type", "datetime");
attributes.Add("class", "text-box single-line");
//since this is a constraint, IsRequired and other constraints
//won't necessarily apply in the browser, but in case script
//turns off readonly we want the constraints passed
if (ViewData.ModelMetadata.IsReadOnly)
{
attributes.Add("readonly", "readonly");
}
if (ViewData.ModelMetadata.IsRequired)
{
attributes.Add("required", "required");
}
}
@Html.TextBox("", Model.HasValue ? Model.Value.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ssZ") : String.Empty, attributes)
对于本地日期:
@model DateTime?
@{
var attributes = new Dictionary<string, object>();
attributes.Add("type", "datetime-local");
attributes.Add("class", "text-box single-line");
if (ViewData.ModelMetadata.IsRequired)
{
attributes.Add("required", "required");
}
}
@Html.TextBox("", Model.HasValue ? Model.Value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss") : String.Empty, attributes)
关于asp.net-mvc - MVC3在opera中将值设置为文本框类型日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9940400/