Dav*_*edy 7 asp.net-mvc customvalidator custom-attributes model-binding data-annotations
我正在开发一个我没有创建的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>
...
Run Code Online (Sandbox Code Playgroud)
问题是当用户选择"国际"时,我得到验证错误,因为两个空格被修剪,State是必填字段.
这是我希望能够做到的:
[Required( ErrorMessage = "State is required" )]
[NoTrim]
public string State { get; set; }
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所获得的属性:
[AttributeUsage( AttributeTargets.Property, AllowMultiple = false )]
public sealed class NoTrimAttribute : Attribute
{
}
Run Code Online (Sandbox Code Playgroud)
在Application_Start中设置了一个自定义模型绑定器:
protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new MyModelBinder();
...
Run Code Online (Sandbox Code Playgroud)
以下是修剪模型活页夹的一部分:
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 );
}
Run Code Online (Sandbox Code Playgroud)
NoTrim 看起来不错,但正是该[Required]
属性会拒绝空格。
requiredAttribute 属性指定当验证表单上的字段时,该字段必须包含一个值。如果属性为 null、包含空字符串 ("") 或仅包含空白字符,则会引发验证异常。
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.aspx
要解决此问题,您可以创建自己的属性版本或使用 RegexAttribute。我不确定该AllowEmptyStrings
物业是否有效。
归档时间: |
|
查看次数: |
2527 次 |
最近记录: |