How to stop auto-population in helper EditorFor?
-
01-06-2021 - |
Question
ViewModel:
[Required]
public int Hours { get; set; }
Razor:
@Html.EditorFor(m => m.Hours)
Output:
<input type="text" value="0" name="Hours" id="Hours"
data-val-required="The field is required."
data-val-number="The field must be a number."
data-val="true" class="text-box single-line valid">
What gives, why is the value being automatically populated with 0. It is pretty much bypassing validation in that the user can submit this without actually entering anything.
Solution
Your property's type is int
which is value type with the default value of 0
.
If you want the Reuired attribute properly work make Hours
nullable:
[Required]
public int? Hours { get; set; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow