C# 从表单提交中删除空白

C# 从表单提交中删除空白,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,当用户填写我的表单以创建一个新的人时,我希望名称前后没有空格(键入String) 好:“约翰·多伊” 坏的:“约翰·多伊”或“约翰·多伊” 从这个角度来看,我似乎想使用一个定制的ModelBinder。然而,我可能错误地理解了这篇文章,替换DefaultModelBinder将意味着所有字符串都不允许有前导或尾随空格 如何确保只有名称受此自定义ModelBinder的影响?您可以使用此函数。 来自MSDN Trim方法从当前字符串中删除所有前导和尾随空格字符 您可以将此行为直接写入视图模型(如果

当用户填写我的表单以创建一个新的人时,我希望名称前后没有空格(键入
String

:“约翰·多伊”

坏的:“约翰·多伊”或“约翰·多伊”

从这个角度来看,我似乎想使用一个定制的ModelBinder。然而,我可能错误地理解了这篇文章,替换DefaultModelBinder将意味着所有字符串都不允许有前导或尾随空格

如何确保只有
名称
受此自定义ModelBinder的影响?

您可以使用此函数。 来自MSDN

Trim方法从当前字符串中删除所有前导和尾随空格字符


您可以将此行为直接写入视图模型(如果您使用的是视图模型):


然后,
名称
将在控制器操作方法中预先修剪。

您可以在属性中为ex:

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get; set; }
然后,您可以在您提到的帖子中为自定义模型活页夹解决方案使用下面修改的代码:

public class TrimModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext,
                                        ModelBindingContext bindingContext,
                                        System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
    {
        if (propertyDescriptor.Name.ToUpper().Contains("NAME")
             && (propertyDescriptor.PropertyType == typeof(string)))
        {
            var stringValue = (string) value;
            if (!string.IsNullOrEmpty(stringValue))
                stringValue = stringValue.Trim();

            value = stringValue;
        }

        base.SetProperty(controllerContext, bindingContext,
                         propertyDescriptor, value);
    }
}

这样,任何名称属性中的名称和字符串类型都将按照您的需要在此处修剪空白。

链接的问题的重点是不要显式修剪()每个字符串,所以我想这里也是这样。不过,我想知道只对一个字段使用如此复杂的方法是否是个好主意。对我来说,模型绑定解决方案听起来有点过分了。@S\u F,既然另一篇文章是按字符串类型搜索的,那么不是每个字符串都被修剪了吗?嗨,阿德里安-谢谢你指出了过度的杀伤力。是的,谢谢。我仍在寻找放置
Trim()
@Kevin你的表单(对话框?)是否有一个“Ok”按钮供用户提交他们填写的内容?我想你只需要在他们实际按下“Ok”或关闭表单的任何按钮时发布他们的姓名。我不确定你所说的Boe标题(打字)是什么意思,但是,最好将类似的代码添加到域/应用程序实体中(或以及)。不过,我不想在DB查询或存储过程中添加任何类似的逻辑。
public class TrimModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext,
                                        ModelBindingContext bindingContext,
                                        System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
    {
        if (propertyDescriptor.Name.ToUpper().Contains("NAME")
             && (propertyDescriptor.PropertyType == typeof(string)))
        {
            var stringValue = (string) value;
            if (!string.IsNullOrEmpty(stringValue))
                stringValue = stringValue.Trim();

            value = stringValue;
        }

        base.SetProperty(controllerContext, bindingContext,
                         propertyDescriptor, value);
    }
}