I've been representing an enum within my razor view as a hidden field, which is posted back to an action result.
I've noticed that when it binds the string value provided within the HTML, it automatically validates the value for the enum.
/// <summary>
/// Quiz Types Enum
/// </summary>
public enum QuizType
{
/// <summary>
/// Scored Quiz
/// </summary>
Scored = 0,
/// <summary>
/// Personality Type Quiz
/// </summary>
Personality = 1
}
Razor:
@Html.HiddenFor(x => x.QuizType)
Rendered HTML:
<input data-val="true" data-val-required="Quiz Type is not valid" id="QuizType" name="QuizType" type="hidden" value="Scored">
If I change the value within the DOM to something incorrect and submit the form, ModelState.IsValid
returns false
and the following error is added to the ModelState:
"The value 'myincorrectvalue' is not valid for QuizType."
That's all gravy, but I thought that if I created a view model, that I had to explicitly set validation rules on my view model, such as the [Required]
attribute.
Also there is a validation attribute specifically for this called EnumDataType
.
[EnumDataType(typeof(QuizType))]
public QuizType QuizType { get; set; }
Question
If validation happens automatically when binding, what is the point in the EnumDataType
data validation attribute?
enum
value is always required (it cant be null) so that why the validation is added. If you don't want it to be required, make it nullablepublic QuizType? QuizType { get; set; }
– Principalnull
, I'm setting it to a value that is not contained in the Enum – Zacekint
is non-nullable, but if I was to set it null it would just be bound as 0... so that doesn't perform auto-validation. Where is it documented which types do/do-not get auto validated? – Zacekint
to an arbitrary string value and it came up with a similar error. I think it must come up with this error for any value that is set to an incorrect value for the type, but it seems that the binding explicitly checks the string value sent from the HTML against the actual text within the enum. If I hadn't have set the value within the HTML at all, then this error wouldn't have been set automatically. – Zacekint
and clear the textbox, you will get a validation error (inspect the html and you will see<input data-val="true" data-val-required="The ID field is required." ...>
even if you dont add the[Required]
attribute – Principal