Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've come up with a solution that works but is clearly a work around.</p> <p>I've removed the validation attribute and created a custom model binder instead which manually adds an error to the <code>ModelState</code> dictionary for the property <code>Group.Name</code>.</p> <pre><code>public class SearchBinder : DefaultModelBinder { protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) { if (propertyDescriptor.Name == "Group" &amp;&amp; bindingContext.ValueProvider.GetValue("Group.Name") != null &amp;&amp; bindingContext.ValueProvider.GetValue("Group.Name").AttemptedValue == "") { ModelState modelState = new ModelState { Value = bindingContext.ValueProvider.GetValue("Group.Name") }; modelState.Errors.Add("Please create a new group or choose an existing one."); bindingContext.ModelState.Add("Group.Name", modelState); } base.BindProperty(controllerContext, bindingContext, propertyDescriptor); } } // Register custom model binders in Application_Start() ModelBinders.Binders.Add(typeof(SearchViewModel), new SearchBinder()); </code></pre> <p>With <code>ModelState["Group.Name"]</code> now having an error entry, the CSS class is being rendered in the markup.</p> <p>I would much prefer if there was a way to do this with idiomatic validation in MVC though.</p> <h2>Solved!</h2> <p>Found a proper way to do this. I was specifying the wrong property name in the self validating class, so the key that was being added to the <code>ModelState</code> dictionary was <code>Group.Group.Name</code>. All I had to do was change the returned <code>ValidationResult</code>.</p> <pre><code>yield return new ValidationResult("Please create a new group or select an existing one.", new[] { "Name" }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload