如何在Html.EditorFor中使用DefaultValueAttribute值?

问题描述

在模型中使用ASP.Net ComponentModelDataAnnotations我有

[required]
[Range(1,50000,ErrorMessage = "Please specify the number of foos.")]
[DefaultValue(1)]
public int Foo { get; set; }

它使用以下方式呈现:

@Html.LabelFor(model => model.Foo)
@Html.EditorFor(model => model.Foo)
@Html.ValidationMessageFor(model => model.Foo,"",new { @class = "text-danger" })

但是呈现的输入字段中的值是0,而不是1指示的DefaultValueAttribute

对此进行研究,this answer提供了两种解决方案:

  1. 通过定义新模型并在视图中设置控制器中的值(推荐并可以使用,但会忽略我在DefaultValueAttribute中的值
  2. 直接使用@value = "1"在“视图”中设置值(不建议这样做,因为它违反了MVC约定)

是否可以将DefaultValueAttribute的值自动呈现到HTML控件中?例如。 @Html帮助方法读取DefaultValueAttribute吗?

解决方法

似乎链接问题中的答案忽略了一些重要的选择:使用模型的构造函数或默认初始化属性:

public class FooModel
{
    public FooModel()
    {
        Foo = 1;
    }

    // Or
    [Required]
    [Range(1,50000,ErrorMessage = "Please specify the number of foos.")]
    public int Foo { get; set; } = 1;
}

根据您的喜好。知识不会从模型泄漏到控制器中,并且在构建模型或随后设置属性时,如果视图未被覆盖,则视图当然会使用该值。