Validating a collection with Dataannotations
Just started on ASP.NET MVC, and I'm开发者_如何学C having some trouble applying datannotations to a collection - I'm either missing something basic, or going about the whole thing in the wrong way.
I have this ViewModel that I pass to a strongly-typed View:
public class AddCostingViewModel
{
[Required]
[Range(120,190)]
public int SomeValue {get; set;}
public List<Grade> Grades { get; set; }
public List<int> GradeValues { get; set; }
}
I have no idea if the number of objects in either grades list will remain constant in the future, so I can't pass in "Grade1, Grade2" etc - passing in a list like this and building up my cshtml page seems like the most obvious way to ensure I always have a form that contains all possible grades, and returns the right values. My cshtml looks something like this:
<tr>
@foreach (var g in Model.Grades)
{
<th>@g.GradeName</th>
}
</tr>
<tr>
@for (int i = 0; i < Model.Grades.Count(); i++)
{
<td>
<div class="editor-field">
@Html.EditorFor(model => model.GradeValues[i])
@Html.ValidationMessageFor(model => model.GradeValues[i])
</div>
</td>
}
</tr>
which handily generates a table containing fields for editing all possible grade values. However, I want to validate these against a range (as with SomeValue above), but adding dataannotations above the list (like I did with SomeValue) doesn't seem to work. Is this possible or is my approach wrong altogether?
As it seems, your grade value is not simple int, it is int with some domain specific restrictions. Following that logic, I would design new class for holding grade value
public class GradeValue
{
[Range(100, 200)]
public int Value { get; set; }
}
And in your model, property that describes list of grade values, would be
public List<GradeValue> GradeValues { get; set; }
And the validation will apply rande to every GradeValue in your viewModel. And in view, you do not have to change any single line of code. Moreover, you could design your GradeValue class
to be implicitely convertible to int and vice versa, for simpler usage.
精彩评论