gpt4 book ai didi

asp.net-mvc - 修剪除具有 NoTrim 属性的输入字段之外的所有输入字段

转载 作者:行者123 更新时间:2023-12-02 03:12:29 25 4
gpt4 key购买 nike

我正在开发一个不是我创建的 ASP.NET MVC 2 应用程序。应用程序中的所有输入字段都会在模型绑定(bind)期间被修剪。但是,我想要一个 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 中设置的自定义模型绑定(bind)器:

protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new MyModelBinder();
...

这是模型 Binder 中进行修剪的部分:

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

最佳答案

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

The RequiredAttribute attribute specifies that when a field on a form is validated, the field must contain a value. A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.

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

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

关于asp.net-mvc - 修剪除具有 NoTrim 属性的输入字段之外的所有输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11441599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com