@Html.EditorFor DateTime not displaying when set a default value to it

自作多情 提交于 2021-02-07 11:42:17

问题


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

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

Controller code:

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

View page:

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

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


回答1:


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

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




回答2:


Your razor would be as follows:

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



回答3:


Change the model to :

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

it is figure out. cause the display format string is not correct.




回答4:


Use DataAnnotations to st default values:

[DefaultValue(System.DateTime.Now)]

public DateTime DateTo { get; set; }


来源:https://stackoverflow.com/questions/33470849/html-editorfor-datetime-not-displaying-when-set-a-default-value-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!