The ThingController creates a model which contains (amongst other properties) a collection of Things. These can be edited in the view like so:
<form action="@Url.Action("Update", "Thing")" method="post">
<table>
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
@foreach (var thing in ViewData.Model.Things)
{
<tr class="raw-data">
<td class="raw-data"><input name="things[@rowCount].Foo" class="raw-data" readonly="readonly" type="text" value="@thing.Foo" /></td>
开发者_JS百科 <td class="raw-data"><input name="things[@rowCount].Bar" class="raw-data" type="text" value="@thing.Bar" /></td>
</tr>
rowCount++;
}
</table>
<br />
<input type="submit" value="OK" />
</form>
The controller contains the following action, which allows multiple Things to be updated simultaneously:
public ActionResult Update(ThingModel[] things)
{
...
}
I've added some validation attributes to properties on the Thing class:
[Required]
[Range(0, 500000, ErrorMessage = "Foo must be within 0 and 500,000.")]
public double Foo{ get; set; }
[Required]
[Range(0, 500000, ErrorMessage = "Bar must be within 0 and 500,000.")]
public double Bar { get; set; }
The thing is, I can't figure out how to add unobtrusive validation using the TextBoxFor helpers etc.
At this point I think the correct approach is to manually mark up the input fields with the validation attributes, but I was wondering if anyone can point me to some documentation, a tutorial etc. that demonstrates the use of helpers, multiple models and unobtrusive validation?
I had a similar problem where users could dynamically add multiple emails to their account. I fixed it with Jquery by adding the validation manually. You should give your form a name and add the validation to all your items. It should be something like this I quess:
$('#frmYourForm').validate();
for (var i = 0; i < 'CountOfAllFields'; i++) {
$('#Things_' + i + '__Foo').rules('add', { required: true, messages: { required: 'The Foo field is required'} });
$('#Things_' + i + '__Bar').rules('add', { required: true, messages: { required: 'The Bar field is required'} });
}
Typed from my memory so don't shoot me if I made an error. I don't know the exact syntax for the Range thingy but you should look around the Jquery.validate file.
精彩评论