@ Html.EditorFor DateTime设置默认值时不显示 [英] @Html.EditorFor DateTime not displaying when set a default value to it

查看:108
本文介绍了@ Html.EditorFor DateTime设置默认值时不显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Controller中为我的模型设置一个默认值,但是它不能显示在创建页面中.

I'd like to set a default value to my model in Controller, But It cannot display in create page.

TestModel代码:

TestModel code:

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

But the display is not correct that it is has no default datetime value, but the description default value is display correct:

推荐答案

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

You need to have model class property like below :

[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 =日期" .

When you decorate a model property with [DataType(DataType.Date)] the default template in ASP.NET MVC generates an input field of type="date".

这篇关于@ Html.EditorFor DateTime设置默认值时不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆