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:
- 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
- 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?