Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is one solution to my problem where I can use the built in required attribute and still get custom behavior. This is just some proof of concept code.</p> <p>The model:</p> <pre><code>public class Page : IPageModel { [Display(Name = "Page", Prompt = "Specify page name...")] [Required(ErrorMessage = "You must specify a page name")] public PageReference PageReference { get; set; } } </code></pre> <p>The model binder:</p> <pre><code>public class PageModelBinder : DefaultModelBinder { protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(bindingContext.ModelType)) { var attributes = property.Attributes; if (attributes.Count == 0) continue; foreach (var attribute in attributes) { if (attribute.GetType().BaseType == typeof(ValidationAttribute) &amp;&amp; property.PropertyType == typeof(PageReference)) { var pageReference = bindingContext.ModelType.GetProperty(property.Name).GetValue(bindingContext.Model, null) as PageReference; Type attrType = attribute.GetType(); if (attrType == typeof (RequiredAttribute) &amp;&amp; string.IsNullOrEmpty(pageReference.Name)) { bindingContext.ModelState.AddModelError(property.Name, ((RequiredAttribute) attribute).ErrorMessage); } } } } base.OnModelUpdated(controllerContext, bindingContext); } } </code></pre> <p>The model binder provider:</p> <pre><code>public class InheritanceAwareModelBinderProvider : Dictionary&lt;Type, IModelBinder&gt;, IModelBinderProvider { public IModelBinder GetBinder(Type modelType) { var binders = from binder in this where binder.Key.IsAssignableFrom(modelType) select binder.Value; return binders.FirstOrDefault(); } } </code></pre> <p>And last the global.asax registration:</p> <pre><code>var binderProvider = new InheritanceAwareModelBinderProvider {     { typeof (IPageModel), new PageModelBinder() }     }; ModelBinderProviders.BinderProviders.Add(binderProvider); </code></pre> <p>The result: <a href="http://cl.ly/IjCS" rel="nofollow">http://cl.ly/IjCS</a></p> <p>So what do you think about this solution?</p>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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