mvc : control specific required validation
I am using mvc 2.0 with C#.Net In my view page, I am creating multiple controls with required field validations. to plot my controls, I am using for loop through my mode object which is actually a collection of business object. For my TextBox control which represent 'user comments', I have put validation under it. like
<%:Html.TextBoxFor(model=>model.mycollection[i].Comment %>
<%:Html.ValidationMessageFor(model => model.mycollection[i].comments) %>
There is a sumit button for each row (for each comment textbox) like below
<input runat="Server" name="Button" id="Submit1" type="submit" class="button" value="save comments">
When the form loads, 3 rows are created, each containing a set of text box and a button to submit. This is because the model is a collection of 3 objects. So now I can submit each comments entered by user individually. But the problem is, when I click on any button, instead of validating corresponding textbox for required validation, it validates all of the textboxes on page at a time and gives error message for all of them. How to avoid this kind of behaviour? Mypage h开发者_运维技巧as a html.beginform method on top to put everything in a single form and to post the submit to an controller action.
Can you try to put each object from your collection in a separate form like this:
<table>
<% foreach(person in Model.Personlist) { %>
<tr>
<td>
<form>
<%=Html.TextAreaFor(...) %>
<%=Html.ValidationMessageFor(...) %>
<input type="button"......></input>
</form>
</td>
</tr>
<% } %>
</table>
..so then only that form will be validated when you click submit. Also you can use divs instead of table .
精彩评论