1

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?

5
  • asp.net/mvc/tutorials/validating-with-a-service-layer--cs this is exactly what I was talking about and trying to accomplish! I knew that someone else out there had to have similar goals in mind. Only took a few days to find it LOL :) Commented Jul 29, 2010 at 16:17
  • Sigh, it looks like you CAN put attributes at the class level...this will also simplify things. Commented Jul 30, 2010 at 16:20
  • Example of class level attributes: byatool.com/mvc/… Commented Jul 30, 2010 at 16:31
  • stackoverflow.com/questions/1607832/… Commented Jul 30, 2010 at 16:44
  • foolproof.codeplex.com Commented Jul 30, 2010 at 18:05

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I think this is more geared to the client side calling the server side for an ajax type remote validation.
@rball: For the record, this is probably the best way to do it. It allows you to immediately confirm that the movie rating is valid, without requiring a full re-render of the entire page. +1
Ok, I'll re-read this and give it a try. This crap sure seems hard!
Still seems to have the attribute required on the property. I feel like I'm still missing something. I think I need to just incorporate what I have above and then loop through in the controller and tack on the extra errors to the model state. That should do it...I just thought there was a better way.
0

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.

11 Comments

The "ASP.NET 2.0 MVC way" you linked was precisely the article that does not explain how to do this, this is more complicated than decorating a property. The 1.0 way looks closer but there's a "The RuleViolation class is a helper class we'll add to the project that allows us to provide more details about a rule violation." So they don't already have a helper class in MVC 2 that does more than what is described in this article? I am not using L2S so I think I'm going to have to have an input model dto with a IsValid property that somehow encapsulates if each of the property decorators and
the custom logic. Either way, thanks for the response, but not the answer I guess I was looking for. I've already done the Google searches for this and haven't found anything helpful.
The first comment actually gets to this and then a response seems to help: 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()); } } }
I was thinking about it again and this still doesn't help. I mean, what property would I put this attribute on? Would I be putting it directly on the class itself somehow? It doesn't relate to any specific property, but more of a process on if the data can be saved.
@rball: That's why I like the MVC 1.0 way of validating things like this. The validation is called when the form is posted, and you can write whatever validation logic in there that you want. Although people like Scott Hanselman dislike it (because it's kind of cut and pastey), it is actually quite effective for scenarios like this, because it encapsulates all of the validation logic in your ViewData object.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.