I’m new to C# and am trying to add some simple server side validation to my site. I’ve tried to Google this, but information is a little thing on the ground.
So for instance, if I values inside of a form like such :
<table>
<tr>
<td>FredF</td>
<td>Fred Flintstone</td>
<td><input type="checkbox" name="userId" value="@user.UserId" /></td>
</tr>
<tr>
<td>BarneyR</td>
<td>Barney Rubble</td>
<td><input type="checkbox" name="userId" value="@user.UserId" /></td>
</tr>
<tr>
<td>WilmaF</td>
<td>Wilma Flintstone</td>
<td><input type="checkbox" name="userId" value="@user.UserId" /></td>
</tr>
</table>
And I want to verify that the user has ticked a checkbox, and if they haven’t, I want a message to be displayed saying they must check the box.
What is best practice for doing this?
Assuming you’re using MVC, best practice for server-side is to use a ViewModel with your form that has an attribute specifying if the property is required or not.
So it would be something like
Then in your Controller Post Action you check Model.IsValid and re-show the form if not.