Reputation: 277
Razor view engine generated default values when a property is non-nullable. So how do I override these default value?
This is the form:
and this is the Model:
public class Movie
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[Required]
[Display(Name="Created on")]
public DateTime DateAdded { get; set; }
[Required]
[Display(Name = "Release Date")]
public DateTime ReleaseDate { get; set; }
[Required]
[Range(1,20)]
[Display(Name = "Number in Stock")]
public int NumberInStock { get; set; }
public Genre Genre { get; set; }
[Required]
[Display(Name="Genre")]
public int GenreId { get; set; }
}
a snippet of one property from the view looks like this:
<div class="form-group">
@Html.LabelFor(m => m.Movie.DateAdded)
@Html.TextBoxFor(m => m.Movie.DateAdded, "{0:d MMM yyyy}", new {
@class = "form-control" })
@Html.ValidationMessageFor(m => m.Movie.DateAdded)
</div>
Upvotes: 0
Views: 397
Reputation: 10532
If you're fine with your model always being populated with a specific default value (so, not only in this view but wherever you create a new instance of your model), then DefaultValueAttribute
is probably the best solution.
e.g.
[Required]
[Display(Name = "Release Date")]
[DefaultValue(typeof(DateTime), "2019-01-01 00:00:00")]
public DateTime ReleaseDate { get; set; }
More info on DefaultValueAttribute
in MSDN.
Upvotes: 1