【问题标题】:@Html.EditorFor DateTime not displaying when set a default value to it@Html.EditorFor DateTime 设置默认值时不显示
【发布时间】:2015-11-02 04:37:47
【问题描述】:

我想在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; }
}

控制器代码:

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值,但描述默认值显示正确:

【问题讨论】:

  • 附件图片为网页展示。
  • 显示TestModel
  • 你需要展示模型。特别是您应用的[DisplayFormat] 属性(格式字符串不正确)

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


【解决方案1】:

你需要有如下模型类属性:

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

【讨论】:

    【解决方案2】:

    你的剃须刀如下:

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

    【讨论】:

    • [DefaultValue(System.DateTime.Now)] public DateTime DateTo { get;放; }
    【解决方案3】:

    将模型更改为:

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

    想通了。导致显示格式字符串不正确。

    【讨论】:

    • 不需要重复拉胡尔尼凯特的回答
    【解决方案4】:

    使用 DataAnnotations 获取默认值:

    [DefaultValue(System.DateTime.Now)]
    
    public DateTime DateTo { get; set; }
    

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 2014-10-09
      • 1970-01-01
      • 2020-10-23
      • 2019-06-13
      相关资源
      最近更新 更多