Setting default values for a Model in MVC3

2019-05-15 04:10发布

问题:

Here's my model's property:

[Required(ErrorMessage = "Debe escribir su fecha de nacimiento")]
[Display(Name = "Fecha de Nacimiento")]
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }

In my AccountController, I create a new object of this model and pass it to the View:

<div class="editor-label">
    @Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.DateOfBirth)
    @Html.ValidationMessageFor(model => model.DateOfBirth)
</div>

Remember, at this point this is a Create form. The model's properties have no values.

However, this is rendered in my HTML.

Is there some way to tell the view engine to not render anything in this field?

回答1:

If you change your definition to a Nullable, then it'll start off as null and no value will be displayed if one isn't set (which by default it isn't).

public DateTime? DateOfBirth { get; set; }