【问题标题】:jQuery form submission extra characters on sent with textarea使用 textarea 发送的 jQuery 表单提交额外字符
【发布时间】:2010-08-18 14:04:07
【问题描述】:

我正在使用http://malsup.com/jquery/form/ 插件通过jQuery 提交一些表单。在这些表格中,我有几个文本区域。我有一个简单的脚本,可以限制可以输入这些文本区域的字符数,这一切都很好。但是,当我提交表单时,查看发送的值时,表单项的大小更大,由于某种原因,添加了额外的 \r\n\,在某些情况下还添加了额外的空格。

有谁知道为什么要添加这些额外的字符,我认为这与数据在发送之前的编码方式有关。

【问题讨论】:

    标签: jquery asp.net-mvc jquery-plugins


    【解决方案1】:

    如果人们添加额外的空格或换行符,任何文本区域都可能会出现此问题。

    我已将 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();
    

    所有变量在到达动作方法时都会被修剪。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      相关资源
      最近更新 更多