Reputation: 26484
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.
Kindest Regards, GONeale
Upvotes: 3
Views: 3227
Reputation: 4290
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. :)
Upvotes: 5
Reputation: 1007
Though not a direct answer to your question, I can offer a little advice: try and use DTOs for passing data between the controller and the view.
You'll find that a lot of third party components and libraries make this assumption, so it will make your life easier in the long run.
By DTOs I'm referring to simple - usually flat - objects, which look something like this:
public class Dto
{
public string PropertyName { get; set; }
public string PropertyNameSubPropertyName { get; set; }
}
For more information, and for a tool to help with the mapping between dtos & domain objects, check out Automapper..
Upvotes: 0