我正在使用http://malsup.com/jquery/form/插件通过jQuery提交一些表单。在这些形式中,我有几个textareas。我有一个简单的脚本,可以限制可以输入这些textareas的字符数,这一切都很好。但是,当我提交表单查看发送的值时,表单项的大小更大,由于某种原因,添加了额外的\ r \ n \,在某些情况下还有额外的空格。
有没有人知道为什么要添加这些额外字符,我认为这与数据在发送之前的编码方式有关。
答案 0 :(得分:0)
如果人们添加额外的空格或换行符,这是任何textarea都可以解决的问题。
我已经用一个修剪任何字符串类型的版本替换了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();
所有变量将在他们到达动作方法时被修剪。