如果人们添加额外的空格或换行符,任何文本区域都可能会出现此问题。
我已将 DefaultModelBinder 替换为修剪任何字符串类型的(这是我在网上找到的修改版本,遗憾的是我没有记下该站点,因此我无法对其进行归因)
public class TrimmingModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext,
System.ComponentModel.PropertyDescriptor propertyDescriptor,
object value) {
string modelStateName = string.IsNullOrEmpty(bindingContext.ModelName) ?
propertyDescriptor.Name :
bindingContext.ModelName + "." + propertyDescriptor.Name;
// only process strings
if (propertyDescriptor.PropertyType == typeof(string))
{
if (bindingContext.ModelState[modelStateName] != null)
{
// modelstate already exists so overwrite it with our trimmed value
var stringValue = (string)value;
if (!string.IsNullOrEmpty(stringValue))
stringValue = stringValue.Trim();
value = stringValue;
bindingContext.ModelState[modelStateName].Value =
new ValueProviderResult(stringValue,
stringValue,
bindingContext.ModelState[modelStateName].Value.Culture);
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
else
{
// trim and pass to default model binder
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, (value == null) ? null : (value as string).Trim());
}
}
else
{
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}
}
然后在 application_start 中像这样钩住它:
ModelBinders.Binders.DefaultBinder = new Kingsweb.Extensions.ModelBinders.TrimmingModelBinder();
所有变量在到达动作方法时都会被修剪。