Asp.net mvc 修剪每个输入字段(具有NoTrim属性的字段除外)

Asp.net mvc 修剪每个输入字段(具有NoTrim属性的字段除外),asp.net-mvc,data-annotations,model-binding,custom-attributes,customvalidator,Asp.net Mvc,Data Annotations,Model Binding,Custom Attributes,Customvalidator,我正在开发一个我没有创建的ASP.NET MVC 2应用程序。在模型绑定期间,应用程序中的所有输入字段都会被修剪。但是,我希望有一个NoTrim属性来防止某些字段被修剪 例如,我有以下状态下拉字段: <select name="State"> <option value="">Select one...</option> <option value=" ">International</option> <

我正在开发一个我没有创建的ASP.NET MVC 2应用程序。在模型绑定期间,应用程序中的所有输入字段都会被修剪。但是,我希望有一个NoTrim属性来防止某些字段被修剪

例如,我有以下状态下拉字段:

<select name="State">
    <option value="">Select one...</option>
    <option value="  ">International</option>
    <option value="AA">Armed Forces Central/SA</option>
    <option value="AE">Armed Forces Europe</option>
    <option value="AK">Alaska</option>
    <option value="AL">Alabama</option>
    ...
以下是到目前为止我对该属性的了解:

[AttributeUsage( AttributeTargets.Property, AllowMultiple = false )]
public sealed class NoTrimAttribute : Attribute
{
}
有一个自定义模型绑定器可在应用程序_Start中设置:

protected void Application_Start()
{
    ModelBinders.Binders.DefaultBinder = new MyModelBinder();
    ...
以下是模型活页夹中进行修剪的部分:

protected override void SetProperty( ControllerContext controllerContext,
                                     ModelBindingContext bindingContext,
                                     PropertyDescriptor propertyDescriptor,
                                     object value )
{
    if (propertyDescriptor.PropertyType == typeof( String ) && !propertyDescriptor.Attributes.OfType<NoTrimAttribute>().Any() )
    {
        var stringValue = (string)value;

        if (!string.IsNullOrEmpty( stringValue ))
        {
            value = stringValue.Trim();
        }
    }

    base.SetProperty( controllerContext, bindingContext, propertyDescriptor, value );
}
protected override void SetProperty(ControllerContext ControllerContext,
ModelBindingContext bindingContext,
PropertyDescriptor PropertyDescriptor,
对象值)
{
if(propertyDescriptor.PropertyType==typeof(String)&&!propertyDescriptor.Attributes.OfType().Any())
{
var stringValue=(字符串)值;
如果(!string.IsNullOrEmpty(stringValue))
{
value=stringValue.Trim();
}
}
SetProperty(controllerContext、bindingContext、propertyDescriptor、value);
}

NoTrim看起来不错,但它的
[必需]
属性将拒绝空白

RequiredAttribute属性指定窗体上的字段 验证后,该字段必须包含一个值。验证异常 如果属性为null、包含空字符串(“”),或 仅包含空白字符

要解决此问题,可以创建自己的属性版本或使用RegeAttribute。我不确定
AllowEmptyStrings
属性是否有效。

我只想用“-1”或“-”之类的内容替换“”即可。 如果这是唯一的情况,当然

这个怎么样

[MinLength(2, ErrorMessage = "State is required")]
[DisplayFormat(ConvertEmptyStringToNull=false)]

@KyleTrauberman,不幸的是我无法控制这方面。必须是空白。它不是由浏览器修剪的,而是在应用程序的某个地方。不小心删除了我的评论:我问是谁在修剪,以及是否可以使用其他东西来代替空白。这个应用程序是否有要修剪的代码,还是MVC在绑定到模型之前进行修剪?@KyleTrauberman请查看更新的问题。这不是一个选项,因为数据不在我手中。仅此而已。最终创建了一个允许空白的自定义NoteNull属性。Require属性可能会拒绝空白,但例如,在输入名称时,可能不需要在额外的空格上使用首字母,因此建议的解决方案是一个很好的解决方案。使用
[StringLength(2,ErrorMessage=“State is required”)]
进行不引人注目的验证。
[MinLength(2, ErrorMessage = "State is required")]
[DisplayFormat(ConvertEmptyStringToNull=false)]