ASP.NET MVC:最好的方式来削减数据录入后的字符串。我应该创建一个自定义的模型绑定? [英] ASP.NET MVC: Best way to trim strings after data entry. Should I create a custom model binder?

查看:151
本文介绍了ASP.NET MVC:最好的方式来削减数据录入后的字符串。我应该创建一个自定义的模型绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC,我想他们是插入到数据库之前要修剪的所有用户输入的字符串字段。而且因为我有很多数据录入形式,我正在寻找一个优雅的方式来修整所有的字符串,而不是明确地修剪每一个用户提供的字符串值。我很想知道如何当人们正在调整字符串。

我想过可能创建一个自定义模型绑定和修剪任何字符串值存在...这样,我所有的修整逻辑包含在一个地方。这是一个很好的方法吗?是否有任何code样品的做到这一点?


解决方案

 公共类TrimModelBinder:DefaultModelBinder
  {
    保护覆盖无效的SetProperty(ControllerContext controllerContext,
      ModelBindingContext BindingContext中,
      System.ComponentModel.PropertyDescriptor的PropertyDescriptor,对象的值)
    {
      如果(propertyDescriptor.PropertyType == typeof运算(字符串))
      {
        VAR stringValue的=(字符串)值;
        如果(!string.IsNullOrEmpty(stringValue的))
          stringValue的= stringValue.Trim();        值= stringValue的;
      }      base.SetProperty(controllerContext,BindingContext中,
                          PropertyDescriptor的,价值);
    }
  }

这个怎么样code?

  ModelBinders.Binders.DefaultBinder =新TrimModelBinder();

设置Global.asax的Application_Start事件。

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.IsNullOrEmpty(stringValue))
          stringValue = stringValue.Trim();

        value = stringValue;
      }

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

How about this code?

ModelBinders.Binders.DefaultBinder = new TrimModelBinder();

Set global.asax Application_Start event.

这篇关于ASP.NET MVC:最好的方式来削减数据录入后的字符串。我应该创建一个自定义的模型绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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