如何在ASP.NET MVC中修改Razor View Engine生成的默认表单值?

时间:2019-04-30 13:31:35

标签: c# asp.net-mvc

当属性不可为空时,

Razor 视图引擎会生成默认值。那么,如何覆盖这些默认值?

这是表格:

enter image description here

这是模型:

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>

1 个答案:

答案 0 :(得分:1)

如果您总是对模型填充特定的默认值(因此,不仅在此视图中,而且无论在何处创建模型的新实例)都可以,那么DefaultValueAttribute可能是最佳解决方案

例如

[Required]
[Display(Name = "Release Date")]
[DefaultValue(typeof(DateTime), "2019-01-01 00:00:00")]
public DateTime ReleaseDate { get; set; }

有关MSDNDefaultValueAttribute的更多信息。