rball
rball

Reputation: 6955

How do I implement ASP.NET MVC 2 validation that checks the database?

All examples that I can find do something like this:

[Required]
public string Title { get; set; }

That's great for simple cases, but what about something that checks the database or something else server side?

For example, say I have a movie database and I want to allow people to rate it. How could I tell if someone has already rated a movie, as I'd only want them to rate a movie once.

I would think it would be something like:

public IEnumerable<string> ValidateUserHasNotAlreadyRatedMovie(User currentUser, Guid movieId)
{
  if(movieHasAlreadyBeenRated)
  {
    yield return "Movie been rated man!";
  }
}

Now then I'd call this with something like:

var errors = new List<string>();
errors.AddRange(ValidateUserHasNotAlreadyRatedMovie(topic, comment));
if(errors.Any())
{
  throw new SomeTypeOfCustomExtension??(errors);
}

Do I just need to extend Exception for a custom SomeTypeOfCustomExtension above, or is there something already built? Am I doing this the ASP.NET MVC 2 way?

After that how do I put it into the model state and let the view know something's wrong?

Upvotes: 1

Views: 174

Answers (2)

Tassadaque
Tassadaque

Reputation: 8199

See this it may help

Remote Validation with ASP.NET MVC 2

http://bradwilson.typepad.com/blog/2010/01/remote-validation-with-aspnet-mvc-2.html

Upvotes: 1

Robert Harvey
Robert Harvey

Reputation: 180777

The ASP.NET 2.0 MVC way of doing custom validation is described here. It basically shows how to write a custom validation attribute. Here is an example of one such custom attribute that checks the database for name uniqueness:

public class UniqueNameAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
        string str = (string)value; 
        if (String.IsNullOrEmpty(str)) 
            return true; 

        using (XDataContext vt = new XDataContext()) 
        { 
            return !(vt.Users.Where(x => x.Username.Equals(str)).Any()); 
        } 
    } 
} 

The ASP.NET 1.0 way (that doesn't require custom attributes) is described here.

Upvotes: 0

Related Questions