views:

70

answers:

3

So, if I want to add a new object to my database, I can write this:

public ActionResult Something(SomeObject Object) {
    if (ModelState.IsValid()) {
        DataContext.SomeObjects.InsertOnSubmit(Object);
        DataContext.SubmitChanges();
    };
}

But, how does validation get called when I want to update an object? Does UpdateModel<T> automatically perform the validation or do I have to do something to tell it to or do I have to do something ahead of calling UpdateModel<t>?

EDIT:

For @SLaks, so do I do something like this:

UpdateModel<SomeObject>(Object);

if (ModelState.IsValid()) {
    DataContext.SubmitChanges();
};

Or, if I'm butchering that, please show me the right way.

+1  A: 

You should check ModelState.IsValid() again.

SLaks
@SLaks, please look at my edit above.
Alex
@Alex: You only want to update the model if it's valid.
SLaks
A: 

Client side validation is the best for informing the user what the problem is. Check out this link. http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

tkerwood
However, you still need server-side validation.
SLaks
@tkerwood, client side validation is "good", but server side is best and absolute. I need to get the server side up and running before I deal with client side implementation.
Alex
+1 for recognizing that, Alex. Client side validation is a nice convenience, but it's always subject to tampering/disabling by the user.
Andrew Barber
+1  A: 

Your original question seemed to be "how does validation get called?".

The validation is called on the object if it implements the IDataErrorInfo interface. IDataErrorInfo is implemented in the Model Binder - this happens just before the execution is passed to your Action.

So, answer in short: You don't have to tell it to do something if your using DataAnnotations. The validation happens automatically before you get to the Action's code. That's why ModelState.IsValid() returns a value - because the validation has completed.

cottsak