0

I Have a MVC Project with a Model named Contact, in create view how can I Check if the new value is exist avoid to register it, is there any Attribute to check it Automatically like [Required] Validator? something like [NoRepeated] ??

tereško
  • 58,060
  • 25
  • 98
  • 150
Saeid
  • 13,224
  • 32
  • 107
  • 173

2 Answers2

1

I think you should make the DB column a unique one. And when duplicates are inserted it will throw an exception . Which you can catch and show to the user as an error.

Illuminati
  • 4,539
  • 2
  • 35
  • 55
  • hmm, I use EFCodefirst, how can I define UK in overriding OnModelCreating method? – Saeid Nov 16 '11 at 10:05
  • here you go, http://stackoverflow.com/questions/5701608/unique-key-with-ef-code-first – Illuminati Nov 16 '11 at 10:34
  • I work with MVC 3 and EF 4 and the code don't recognize ExecuteSqlCommand in context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX IX_Category_Title ON Categories (Title)"); is this about version or otherthing? – Saeid Nov 16 '11 at 10:46
  • did u execute the exact same query? you need to provide proper table name instead of "Categories" and your column name instead of "Title" – Illuminati Nov 16 '11 at 10:53
  • I know about the query, but the main problem is in context.Database the ExecuteSqlCommand not Exist.?? – Saeid Nov 16 '11 at 11:01
  • Hmm This is all about the version – Saeid Nov 16 '11 at 11:54
0

There is no way of doing this automatically for you, since you have to query your database. You can do this via Ajax directly from your view and in any case also after the view is posted.

See the following link to get started writing a custom ValidationAttribute which does a similar thing: http://devermind.wordpress.com/2010/01/11/asp-net-mvc-tip-4-client-side-form-validation-made-easy-part-2/

kay.herzam
  • 3,053
  • 3
  • 26
  • 37