@ Html.EditorFor DateTime在设置默认值时不显示

问题描述 投票:7回答:4

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

TestModel代码:

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; }
}

控制器代码:

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

c# asp.net-mvc model string-formatting data-annotations
4个回答
4
投票

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

[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="date"的输入字段。


0
投票

将模型更改为:

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

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


    public string Description { get; set; }
}

它是搞清楚的。导致显示格式字符串不正确。


0
投票

你的剃刀如下:

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

-1
投票

将DataAnnotations用于st默认值:

[DefaultValue(System.DateTime.Now)]

public DateTime DateTo { get; set; }
© www.soinside.com 2019 - 2024. All rights reserved.