Kevin Meredith
Kevin Meredith

Reputation: 41909

Removing Whitespace from Form Submission

When a user fill out my form to create a new Person, I'd like there to be no whitespace before or after a name (type String).

Good: "John Doe"

Bad: "John Doe " or " John Doe"

Looking at this SO post, it seems that I want to use a custom ModelBinder. However, as I perhaps incorrectly understand the post, replacing my DefaultModelBinder will mean that all strings will not be allowed to have leading or trailing whitespace.

How can I ensure that only Name's are affected by this custom ModelBinder?

Upvotes: 0

Views: 1802

Answers (3)

Yogiraj
Yogiraj

Reputation: 1982

You can have have name mentioned in property for ex:

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get; set; }

And then you can use the modified code below for the Custom Model binder solution in the post you have mentioned:

public class TrimModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext,
                                        ModelBindingContext bindingContext,
                                        System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
    {
        if (propertyDescriptor.Name.ToUpper().Contains("NAME")
             && (propertyDescriptor.PropertyType == typeof(string)))
        {
            var stringValue = (string) value;
            if (!string.IsNullOrEmpty(stringValue))
                stringValue = stringValue.Trim();

            value = stringValue;
        }

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

This way any name property that name in it and is type of string will have the white spaces trimmed as you want here.

Upvotes: 0

Adrian Thompson Phillips
Adrian Thompson Phillips

Reputation: 7141

You could write this behaviour straight into your view-model (if you're using view-models):

private string name;

public string Name
{
    get { return this.name; }

    set { this.name = value.Trim(); }
}

Then the Name will arrive pre-trimmed in your controller action method.

Upvotes: 2

young
young

Reputation: 2181

You can use Trim function. From MSDN,

The Trim method removes from the current string all leading and trailing white-space characters.

Upvotes: 0

Related Questions