Search code examples
asp.net-mvcasp.net-mvc-5

How to use DefaultValueAttribute value within Html.EditorFor?


Using ASP.Net ComponentModel and DataAnnotations within a model, I have:

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

It is rendered using:

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

But the value within the rendered input field is 0 and not 1 as directed by the DefaultValueAttribute.

Researching this, this answer provides two solutions:

  1. Set the value in the Controller by defining a new model and pass to the view (recommended, and works, but ignores my value within the DefaultValueAttribute
  2. Set the value in the View directly using @value = "1" (not recommended as it breaks the MVC convention)

Is it possible to render the DefaultValueAttribute's value into the HTML control automatically? E.g. the @Html helper methods read the DefaultValueAttribute?


Solution

  • It seems like the answers in the linked question omit some important options: using the model's constructor, or default initialising the property:

    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;
    }
    

    Whichever you prefer. The knowledge of that doesn't leak from your model into the controller, and the view will of course use that value if it's not been overwritten, either when constructing the model or setting the property afterwards.