数据输入后修剪字符串的最佳方法.我应该创建自定义模型绑定器吗? [英] Best way to trim strings after data entry. Should I create a custom model binder?

查看:24
本文介绍了数据输入后修剪字符串的最佳方法.我应该创建自定义模型绑定器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ASP.NET MVC,我希望在将所有用户输入的字符串字段插入数据库之前对其进行修剪.由于我有许多数据输入表单,我正在寻找一种优雅的方式来修剪所有字符串,而不是显式修剪每个用户提供的字符串值.我很想知道人们如何以及何时修剪字符串.

I'm using ASP.NET MVC and I'd like all user entered string fields to be trimmed before they're inserted into the database. And since I have many data entry forms, I'm looking for an elegant way to trim all strings instead of explicitly trimming every user supplied string value. I'm interested to know how and when people are trimming strings.

我想过也许创建一个自定义模型绑定器并在那里修剪任何字符串值……这样,我的所有修剪逻辑都包含在一个地方.这是一个好方法吗?是否有任何代码示例可以做到这一点?

I thought about perhaps creating a custom model binder and trimming any string values there...that way, all my trimming logic is contained in one place. Is this a good approach? Are there any code samples that do this?

推荐答案

  public class TrimModelBinder : DefaultModelBinder
  {
    protected override void SetProperty(ControllerContext controllerContext, 
      ModelBindingContext bindingContext, 
      System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
    {
      if (propertyDescriptor.PropertyType == typeof(string))
      {
        var stringValue = (string)value;
        if (!string.IsNullOrWhiteSpace(stringValue))
        {
          value = stringValue.Trim();
        }
        else
        {
          value = null;
        }
      }

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

这个代码怎么样?

ModelBinders.Binders.DefaultBinder = new TrimModelBinder();

设置 global.asax Application_Start 事件.

Set global.asax Application_Start event.

这篇关于数据输入后修剪字符串的最佳方法.我应该创建自定义模型绑定器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆