Lib*_*tal 2 asp.net-mvc datetime textbox input asp.net-mvc-3
我的ASP.NET MVC3应用程序中有datetime输入:
<div class="editor-field">
@Html.EditorFor(model => model.Article.PublishedDate)
@Html.ValidationMessageFor(model => model.Article.PublishedDate)
</div>
Run Code Online (Sandbox Code Playgroud)
在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=""/>
Run Code Online (Sandbox Code Playgroud)
我怎样才能修复它并在Opera中设置日期时间?
HTML5输入日期时间规范:http://dev.w3.org/html5/markup/input.datetime.html
所以你的价值需要像这样形成:
<input ... type="datetime" value="2012-03-30T10:00:00" ... />
Run Code Online (Sandbox Code Playgroud)
要将日期格式化为RFC3339,您可以调用:
DateTime.ToString("yyyy-MM-ddThh:mm:ssZ");
Run Code Online (Sandbox Code Playgroud)
您可以通过向Article.PublishedDate添加DisplayFormatAttribute来实现此目的:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-ddThh:mm:ssZ}")]
public DateTime PublishedDate { get; set; }
Run Code Online (Sandbox Code Playgroud)
现在的问题(至少对我来说)是现在这个属性总是像这样形成.您可以使用EditorFor Template:
@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)
Run Code Online (Sandbox Code Playgroud)
对于当地日期:
@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)
Run Code Online (Sandbox Code Playgroud)