Reputation: 13047
I am having an issue with validation in EF models, that I cannot quite seem to figure out. The unobtrusive Javascript validation part works as expected.
Consider the following models (the RequiredIf
attribute is from this library):
public class Conversation
{
public int Id { get; set; }
public User User { get; set; }
public String Handler { get; set; }
}
[ComplexType]
public class User
{
public bool Anonymous { get; set; }
[RequiredIf("Anonymous", false)]
[Display(Name = "Full name")]
public String Name { get; set; }
}
My editor view only shows fields for User
, and this is my controller.
[HttpPost()]
public ActionResult Create(Conversation conversation)
{
if (ModelState.IsValid)
{
_db.Conversations.Add(conversation);
_db.SaveChanges(); // fails on this line
}
return RedirectToAction("Index");
}
This results in the following error:
DbUnexpectedValidationException: An unexpected exception was thrown during validation of 'Full name' when invoking Mvc.ValidationToolkit.RequiredIfAttribute.IsValid. See the inner exception for details.
And the inner exception:
Member 'Conversation.Anonymous' not found.
Why is the validation suddenly looking for Conversation.Anonymous
, and not Conversations.Client.Anonymous
?
Upvotes: 1
Views: 255
Reputation: 33071
You shouldn't be using your entities directly in your view. Create a View Model that is specific to your views and then use something like AutoMapper to map the domain objects to your view models. Put all the required, length, etc. validations on your view model.
var model = Mapper.Map<Conversation, ConversationViewModel>(conversation);
return View(model);
Upvotes: 2