2

I have an int array in my Model. Is it possible to use the Range attribute on it in order to do client-side data validation?

I would like to do something like this:

[Display(Name = "Maths grade")]
[Range(1, 5, ErrorMessage = "Every grade must be between 1 and 5")]
public int[] Maths { get; set; }

How can I do something like this? Thanks for any help!

0

1 Answer 1

2

You cannot apply the attribute to an array and get client side validation because the elements you generating in the view are of each item in the array, not the array itself The way to achieve both client and server side validation would be to have a model property for the value and apply the attribute to that property

public class MathModel
{
    Display(Name = "Maths grade")]
    [Range(1, 5, ErrorMessage = "The grade must be between 1 and 5")]
    public int Grade { get; set; }
}

and in your main model

public List<MathModel> Maths { get; set; }

and in the view

@for(int i = 0; i < Model.MathModel.Count; i++)
{
    @Html.LabelFor(m => m.MathModel[i].Grade)
    @Html.TextBoxFor(m => m.MathModel[i].Grade)
    @Html.ValidationMessageFor(m => m.MathModel[i].Grade)
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.