Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Jun 25, 2012 06:48 PM by rjdudley
Jun 25, 2012 03:01 PM|LINK
I am new to MVC, but have been doing Web Forms for a long time. One item I need to know, and am hoping some one has a link to a nice step by step, is how to validate an entry is unique in a table.
In Web Forms I would do this with a custom validation control and a method in the code behind. I obtain the id of the record being edited, or default it to 0 or -1 if it is a new record. You have to account for the id because you will want to ignore the
record you are editing to check for uniqueness.
Jun 25, 2012 06:41 PM|LINK
You can do this in your controller methods. For instance, when the Create view is submitted, you can query the database or EF model. If the ID is unique, you can insert. If not, display an error message on your view.
Out of cusiosity, why don't use put a UNIQUE constraint in the database and bubble the error back up to the UI?
Jun 25, 2012 06:45 PM|LINK
I did not realize I could do validation in the controller's HttpPost, I'll need to keep that in mind.
As to why I didn't use a UNIQUE constraint. I hate to admit, I forgot all about that! Thank you very much.
Jun 25, 2012 06:48 PM|LINK
At its core, validation is just a method to check data run at the proper time to do so. There isn't a validator
per se in the controller mothods, but you can execute a query and throw an exception.