c# - @Html.EditorFor DateTime 在为其设置默认值时不显示

标签 c# asp.net-mvc model string-formatting data-annotations

我想在 Controller 中为我的模型设置一个默认值,但它无法在创建页面中显示。

测试模型代码:

public class TestModel
{
    [DataType(DataType.DateTime), Required]
    [DisplayFormat(DataFormatString = "yyyy/MM/dd", ApplyFormatInEditMode = true)]
    public DateTime StartTime { get; set; }

    [DataType(DataType.DateTime), Required]
    [DisplayFormat(DataFormatString = "yyyy/MM/dd", ApplyFormatInEditMode = true)]
    public DateTime EndTime { get; set; }


    public string Description { get; set; }
}

Controller 代码:

public ActionResult Create()
{
    var model = new TestModel();
    model.StartTime = DateTime.Now;
    model.EndTime = DateTime.Now.AddDays(10);
    model.Description = "This is a default value";
    return View(model);
}

查看页面:

<div class="form-group">
    @Html.LabelFor(model => model.StartTime, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.StartTime)
        @Html.ValidationMessageFor(model => model.StartTime)
    </div>
</div>

但显示不正确,它没有默认的 datetime 值,但描述默认值显示正确: enter image description here

最佳答案

您需要具有如下模型类属性:

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

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

当您使用 [DataType(DataType.Date)] 修饰模型属性时,ASP.NET MVC 中的默认模板会生成 type= 的输入字段“日期”

关于c# - @Html.EditorFor DateTime 在为其设置默认值时不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470849/

相关文章:

c# - 使用 LINQ 对列表进行排序,除了一个条目

c# - LINQ 到 SQL : On load processing of lazy loaded associations

c# - 从数据库中检索用户并转换为用户对象

c# - Umbraco 媒体没有批准的文件类型

c# - 使用 HttpPostedFile 编辑 View 模型绑定(bind)

c# - asp.net 工具提示对于里面的文本来说显得很大

c# - 反汇编托管代码问题

javascript - MVC中AJAX请求后如何刷新div?

ruby - 使用 Redis 的 Rails 4 简单模型缓存

ruby-on-rails-3 - 从类方法 : "undefined method" 调用辅助方法