首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在数据输入后裁剪字符串的最好方法。我应该创建一个自定义的模型绑定器吗?

在数据输入后裁剪字符串的最好方法。我应该创建一个自定义的模型绑定器吗?
EN

Stack Overflow用户
提问于 2009-11-12 06:25:40
回答 11查看 55K关注 0票数 185

我正在使用ASP.NET MVC,我希望所有用户输入的字符串字段在插入到数据库之前都被修剪掉。因为我有许多数据输入表单,所以我正在寻找一种优雅的方法来裁剪所有字符串,而不是显式地裁剪每个用户提供的字符串值。我很有兴趣知道人们是如何以及何时修剪字符串的。

我想也许可以创建一个自定义模型绑定器,并以there...that方式修剪任何字符串值,我所有的修剪逻辑都包含在一个地方。这是一种好的方法吗?有没有代码样本可以做到这一点?

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2009-11-14 19:50:22

  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.IsNullOrWhiteSpace(stringValue))
        {
          value = stringValue.Trim();
        }
        else
        {
          value = null;
        }
      }

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

这段代码怎么样?

ModelBinders.Binders.DefaultBinder = new TrimModelBinder();

设置global.asax Application_Start事件。

票数 223
EN

Stack Overflow用户

发布于 2011-05-29 04:39:27

这是@takepara相同的解决方案,但作为IModelBinder而不是DefaultModelBinder,因此在global.asax中添加模型绑定器是通过

ModelBinders.Binders.Add(typeof(string),new TrimModelBinder());

类:

public class TrimModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext,
    ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueResult== null || valueResult.AttemptedValue==null)
           return null;
        else if (valueResult.AttemptedValue == string.Empty)
           return string.Empty;
        return valueResult.AttemptedValue.Trim();
    }
}

基于@haacked帖子:http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx

票数 79
EN

Stack Overflow用户

发布于 2011-05-31 03:38:18

对@takepara答案的一项改进。

一些人在项目中:

public class NoTrimAttribute : Attribute { }

在TrimModelBinder中更改类

if (propertyDescriptor.PropertyType == typeof(string))

if (propertyDescriptor.PropertyType == typeof(string) && !propertyDescriptor.Attributes.Cast<object>().Any(a => a.GetType() == typeof(NoTrimAttribute)))

您还可以使用NoTrim属性标记要从修剪中排除的属性。

票数 47
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1718501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档