views:

20

answers:

1

I'm using the http://malsup.com/jquery/form/ plugin to submit some forms via jQuery. Within these forms I have a couple of textareas. I have a simple script that limits the number of characters that can be entered into these textareas and this all works fine. However when I submit the form looking at the value that gets sent the form item size is larger, for some reason extra \r\n\ have been added and in some cases extra spaces.

Does any know why these extra characters are added, I assume it's some to do with the way the data is encoded before it's sent.

A: 

This is an issue you could get with any textarea if people add extra spaces or newlines.

I've replaced the DefaultModelBinder with one that trims any string type (this is a modified version of one I found online unfortunately I didn't make a note of the site so I can't attribute it)

public class TrimmingModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext,
                                        ModelBindingContext bindingContext,
                                        System.ComponentModel.PropertyDescriptor propertyDescriptor,
                                        object value) {
        string modelStateName = string.IsNullOrEmpty(bindingContext.ModelName) ?
            propertyDescriptor.Name :
            bindingContext.ModelName + "." + propertyDescriptor.Name;

        // only process strings
        if (propertyDescriptor.PropertyType == typeof(string))
        {
            if (bindingContext.ModelState[modelStateName] != null)
            {
                // modelstate already exists so overwrite it with our trimmed value
                var stringValue = (string)value;
                if (!string.IsNullOrEmpty(stringValue))
                    stringValue = stringValue.Trim();

                value = stringValue;
                bindingContext.ModelState[modelStateName].Value =
                  new ValueProviderResult(stringValue,
                    stringValue,
                    bindingContext.ModelState[modelStateName].Value.Culture);
                base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
            }
            else
            {
                // trim and pass to default model binder
                base.SetProperty(controllerContext, bindingContext, propertyDescriptor, (value == null) ? null : (value as string).Trim());
            }
        }
        else
        {
            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
        }
    }
}

Then in application_start just hook it in like this:

ModelBinders.Binders.DefaultBinder = new Kingsweb.Extensions.ModelBinders.TrimmingModelBinder();

And all your variables will be trimmed by the time they get to the action methods.

Chao