ASP.NET MVC Bind Exclude Not Working on Nested Object in View Model?

.net, asp.net-mvc-3, c#, model-binding

Solution

The `[Bind]` attribute only affects model binding. That is, whether or not the ASP.NET MVC framework will try and populate the property from the request.

Your issue is related to validation - a whole other beast. :)

Problem

I have been getting problems like these for a while but once and for all would like to know what's going on :) I have a simple ASP.NET MVC view which is bound to a view model class `MemberViewModel`. `MemberViewModel` contains a Linq To Sql entity object that my form is primarily bound to named `Member`, however I do have about three other form fields bound to a child class named `Member.User`. `Member` contains personal info about the user, and `Member.User` contains Username + Password information, both of which are stored in separate tables in the DB. Now as I stated the view's model object uses a custom view-model class entitled `MemberViewModel`, the contents of which are as follows: ``` [Bind(Exclude = "EncryptedPassword")] public class MemberViewModel : ViewModel { public Member Member { get; set; } public string Password { get; set; } [DisplayName("Confirm Password")] public string ConfirmPassword { get; set; } public MemberViewModel() { } public MemberViewModel(Member member, SelectList countryList) { Member = member; CountryList = countryList; } } ``` You can see how there is only a single reference to `Member`. Member is a Linq to Sql object and inside it has it's reference to `User`. `Password` + `ConfirmPassword` and form only fields and do not have an equivalent counterpart in Linq To Sql. Now my problem is, whenever I submit the form my `ModelState.IsValid` property always returns false stating the model error being `The EncryptedPassword field is invalid`. Now regardless of whether I add `[Bind(Exclude = "Member.User.EncryptedPassword")]` to my `MemberViewModel` as a class attribute, or on the partial class for `User` itself as `[Bind(Exclude = "EncryptedPassword")]` the `ModelState.IsValid` continually states it is invalid. - How can I get this to function and exclude child properties from model state validation? - How does Bind Exclude truly work and what is the best practice for child objects and working with model binding in conjunction with view models? Kindest Regards, GONeale

Original source