开发者

How to use ModelState.IsValid with complex objects?

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开发者_JAVA百科 the ClientId and bind it to the Campaign?


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)


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/


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜