Html.ValidationSummary showing duplicate error messages
I have searched and Googled for the answer to this question to no avail. I'm using EF4 and ASP.NET M开发者_JAVA百科VC2 and I have an EF4 entity "Award" with a non-nullable string field, "RecipientID". I'm using DataAnnotations for server-side validation, so in my "Award" partial class I've set up the RecipientID to have the Required attribute. When I try to submit the form with the RecipientID text box empty, I see my error message "Please enter a recipient" in the Html.ValidationSummary twice.
Would this be because the error is being thrown both by the entity (in that it is a non-nullable field with a null value), as well as the application? Whatever the reason, is there a way to "fix" this and have the error message show up only once? (Fix being in quotations because I'm not sure if this is intended behavior or not.) I didn't think it would be necessary to include relevant code, but I will if it's needed.
Thank you in advance for your help.
It looks like this is intended, according to Brad Wilson. I should have searched for "ConstraintException" and EF4. :)
According to Brad, input validation is fired before the model is bound resulting in the "Required" error to be thrown. In addition, these fields are non-nullable, meaning they throw the same "Required" during model-binding. In my opinion, it's a bit confusing that it would show the same message specified in the "Required" attribute, rather than a SQL exception message, since it makes it look like the same error. Which it most certainly is not. That's where the ConstraintException comes in. In order to prevent the duplicate messages, simply wrap your model-binding code like so:
if (ModelState.IsValid) {
ValidateModel(award);
repository.Add(award);
repository.Save();
}
Simple as that. Thanks!
I found that using ModelState.Clear(); worked when having a similar issue.
精彩评论