简体   繁体   中英

Displaying error messages using C# with Razor

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?

That depends on many factors, like are you using a model, are you using jquery and do you have client side validation enabled.

Read this article:

http://www.codeproject.com/Articles/344292/ASP-NET-MVC3-Razor-With-JQuery-For-Beginners

http://www.asp.net/mvc/tutorials/overview/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript

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

class User
{
    [Required]         
    public bool IsChecked{get;set;}
}

Then in your Controller Post Action you check Model.IsValid and re-show the form if not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM