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>
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.
eg
[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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.