我正在使用ASP.NET MVC,我希望所有用户输入的字符串字段在插入到数据库之前都被修剪掉。因为我有许多数据输入表单,所以我正在寻找一种优雅的方法来裁剪所有字符串,而不是显式地裁剪每个用户提供的字符串值。我很有兴趣知道人们是如何以及何时修剪字符串的。
我想也许可以创建一个自定义模型绑定器,并以there...that方式修剪任何字符串值,我所有的修剪逻辑都包含在一个地方。这是一种好的方法吗?有没有代码样本可以做到这一点?
发布于 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事件。
发布于 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
发布于 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属性标记要从修剪中排除的属性。
https://stackoverflow.com/questions/1718501
复制相似问题