【发布时间】: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