0

This question must have been asked before but couldn't find it.

I know that by creating a custom model binder, I can process data entered by users. There are examples of trimming string properties. Here's an example of that: ASP.NET MVC: Best way to trim strings after data entry. Should I create a custom model binder?

My question is how to control when to process or not process by using custom attributes.

For example, I may want to automatically capitalize the first letter of string properties only if I have an attribute that indicates it like below:

public class MyModel
{
   [CapitalizeFirstLetter]
   public string FirstName { get; set; }

   [CapitalizeFirstLetter]
   public string LastName { get; set; }

   public string UserName { get; set; }
}

In this example, first and last name properties will get processed but not the username although all three are string properties.

How do I handle this?

Community
  • 1
  • 1
Sam
  • 26,817
  • 58
  • 206
  • 383
  • I dont really understand what you are asking here, "when to process or not process", can you provide a better explanation ? – MrVoid Jan 24 '17 at 06:04

1 Answers1

1

You would want to check the property to see if it has the specific Attribute set:

public class CapitalizeFirstLetterModelBinder : DefaultModelBinder
{
    protected override void SetProperty(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext, 
        System.ComponentModel.PropertyDescriptor propertyDescriptor,
        object value)
    {
        if (propertyDescriptor.Attributes.Any(att => typeof(att) == typeof(CapitalizeFirstLetterAttribute))
        {
            var stringValue = (string)value;
            if (!string.IsNullOrWhiteSpace(stringValue))
            {
                value = stringValue.First().ToString().ToUpper() + stringValue.Substring(1);
            }
            else
            {
                value = null;
            }
        }

        base.SetProperty(controllerContext, bindingContext, 
                      propertyDescriptor, value);
    }
}
Nick Coad
  • 3,623
  • 4
  • 30
  • 63