Razor 视图引擎会生成默认值。那么,如何覆盖这些默认值?
这是表格:
这是模型:
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; }
}
该视图中一个属性的摘要如下:
<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>
答案 0 :(得分:1)
如果您总是对模型填充特定的默认值(因此,不仅在此视图中,而且无论在何处创建模型的新实例)都可以,那么DefaultValueAttribute
可能是最佳解决方案
例如
[Required]
[Display(Name = "Release Date")]
[DefaultValue(typeof(DateTime), "2019-01-01 00:00:00")]
public DateTime ReleaseDate { get; set; }
有关MSDN中DefaultValueAttribute
的更多信息。