【问题标题】:Trim every input field except those with NoTrim attribute修剪除具有 NoTrim 属性的输入字段之外的所有输入字段
【发布时间】:2012-07-11 14:22:43
【问题描述】:

我正在开发一个不是我创建的 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>
    ...

问题是当用户选择“国际”时,我得到一个验证错误,因为两个空格被修剪并且状态是必填字段。

这是我想做的事情:

    [Required( ErrorMessage = "State is required" )]
    [NoTrim]
    public string State { get; set; }

这是我目前所获得的属性:

[AttributeUsage( AttributeTargets.Property, AllowMultiple = false )]
public sealed class NoTrimAttribute : Attribute
{
}

在 Application_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 );
}

【问题讨论】:

  • @KyleTrauberman,不幸的是我无法控制这方面。它必须是空格。它不是由浏览器修剪,而是在某处的应用程序中修剪。
  • 不小心删除了我的评论:我问是谁在做修剪,是否可以用其他东西代替空格。
  • 这个应用程序是否有代码要修剪,还是 MVC 在绑定到模型之前进行修剪?
  • @KyleTrauberman 请查看更新后的问题。

标签: asp.net-mvc data-annotations model-binding custom-attributes customvalidator


【解决方案1】:

这个怎么样?

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

【讨论】:

  • 使用[StringLength(2, ErrorMessage = "State is required")] 代替不显眼的验证。
【解决方案2】:

我只是将“”替换为“-1”或“-”之类的东西。 如果这是唯一的情况,当然……

【讨论】:

  • 这不是一个选项,因为我无法控制数据。
【解决方案3】:

NoTrim 看起来不错,但 [Required] 属性会拒绝空格。

RequiredAttribute 属性指定当表单上的字段 已验证,该字段必须包含一个值。验证异常 如果属性为 null、包含空字符串 ("") 或 仅包含空白字符。

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx

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

【讨论】:

  • 就是这样。最终创建了一个允许空格的自定义 NoteNull 属性。
  • Require 属性可能会拒绝空格,但 f.e.输入姓名时,可能不需要额外的空格,因此建议的解决方案是一个很好的解决方案。
猜你喜欢
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多