First of all, I have to say that I understand how Data Annotation-based model validation works in ASP.NET MVC4, and I have successfully implemented it using DataAnnotationsModelValidatorProvider . Therefore, I do not need help with the setup.
But when it comes to HtmlHelpers , I struggle to understand the context of the error message. And by saying context , I mean what kind of error we're talking about. Which attribute returned the error?
What I can get is the Key for the error and the current ErrorMessage , but programmatically, there is nothing that, at least, I know, will bind the error that we are talking about. Whether it is a Required attribute or some other attribute, there is no way to determine how to distinguish them.
Release the script a bit. I have a custom HtmlHelpers for rendering ContentEditable elements. For example, Html.ContentEditableValidationMessageFor(m => m.firstName); . It will output something like this:
<span contenteditable="true" data-valmsg-for="firstName" data-valmsg-replace="Please provide first name" class="field-validation-error">Please provide first name</span>
Now I have a jQuery plugin for processing and saving changes to the ContentEditable element, and it will be saved in the backend. However, there is nothing in the user interface that could tell which error message we are talking about. People can easily see this RequiredAttribute , but programmatically there is no data to distinguish it from some MinLengthAttribute for example.
In this case, if I just used data-valmsg-for="firstName" as the key for localization, this will return the same error message for all errors related to the same property.
To deploy it
What would be the best practice when a ModelState is available to emit a unique identifier for ModelError? Given that I am using ASP.NET MVC4 and DataAnnotationsModelValidatorProvider .
I can think of many ways to “hack it together”, but I would like to use ModelState and everything that MVC provides. If it all comes down to writing a custom ModelValidatorProvider , then I'm all open to it. So far, this is the best and most sustainable way to get around this. I’m all for doing more now and less later than hacking it now and hacking it forever so that it works