views:

569

answers:

2

I'm using ASP.NET MVC and I'd like all user entered string fields to be trimmed before they're inserted into the database. And since I have many data entry forms, I'm looking for an elegant way to trim all strings instead of explicitly trimming every user supplied string value. I'm interested to know how and when people are trimming strings. I thought about perhaps creating a custom model binder and trimming any string values there...that way, all my trimming logic is contained in one place. Is this a good approach? Are there any code samples that do this?

Thanks in advance.

A: 

The best way is to extend .ToString() method in C# 3.0 so that it implements the trim functionality also. This way you dont have to explicitly call Trim method. This is C# 3.0 using Extension methods.

Rasik Jain
Thanks Rasik, but I'm not calling ToString() on any of the fields and as far as I can tell from the MVC source code, nor is the model binder doing that. If I am to depend on an extended version of ToString() for trimming, then I would have to loop through the properties of my model (after binding happens) and call ToString() on all of the strings, which would seem to add a lot of overhead. Did I mis-understand your suggestion?
JohnnyO
-1 for saying 'the best way'
Simon_Weaver
+5  A: 
  public class TrimModelBinder : DefaultModelBinder
  {
    protected override void SetProperty(ControllerContext controllerContext, 
      ModelBindingContext bindingContext, 
      System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
    {
      if (propertyDescriptor.PropertyType == typeof(string))
      {
        var stringValue = (string)value;
        if (!string.IsNullOrEmpty(stringValue))
          stringValue = stringValue.Trim();

        value = stringValue;
      }

      base.SetProperty(controllerContext, bindingContext, 
                          propertyDescriptor, value);
    }
  }

How about this code?

ModelBinders.Binders.DefaultBinder = new TrimModelBinder();

Set global.asax Application_Start event.

takepara
This is exactly what I was looking for. Works beautifully. Thanks.
JohnnyO
i'd just replace the code in the inner most {} with this for brevity: string stringValue = (string)value; value = string.IsNullOrEmpty(stringValue) ? stringValue : stringValue.Trim();
Simon_Weaver
Works for me as well . thanks
mazhar kaunain baig