views:

57

answers:

4

I'm using NHibernate and I've got a Campaign class and it has a Client class as one of its members and I'm attempting to use ModelState.IsValid in my [HttpPost] public Create (CreateCampaignViewModel vm) method.

As my ViewModel contains the object Campaign ModelStats.IsValid is always false as I'm passing the Client.Id from the form instead of the entire Client object.

Is there a way to have it load the Client member before it runs the validation code that sets ModelState.IsValid? Or is there a way to refresh the state of ModelState after I 'manually' retrieve the client object based on the ClientId and bind it to the Campaign?

A: 

Steven Sanderson has a blog post on just this. He removes any of the items which do not have incoming values from the errors collection.

http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/

amarsuperstar
A: 

Try using one of the overloads on the controller's UpdateModel method. Then call ModelState.IsValid.

Tyler Jensen
A: 

I believe SharpArch has a modelbinder that can load the NH objects. But, I don't like that idea very much...instead I'd use a separate PostModel to hold the posted form values. If you re-use the ViewModel to also hold the post data, you'll usually have a lot of fields that make no sense to be posted (like the Client object in your example) or readonly display fields.

class CampaignPostModel{
    ...
    public int ClientId { get; set; }
}

All you need to do is match-up the property names to the form input names and add this as a parameter on your post action method.

dotjoe
+1  A: 

You probably want to add an attribute to the parameter of your action method, to disable binding of the Id:

[HttpPost]
public Create([Bind(Ignore="ClientId")]CreateCampaignViewModel vm)
Tomas Lycken