【www.gdgbn.com--php函数】

.net 中为我们提供了三个字符串处理函数,相信大家一定都用过:trim、trimstart、trimend。

但在实际应用中,逐个 trim 是相当麻烦的。我们来分析下,请看如下 controller 及其 model:

public class personcontroller : controller
{
    public actionresult query(string name)
    {
        //...
    }
    //...
    [httppost]
    public actionresult create(person person)
    {
        //...
    }
    [httppost]
    public actionresult create2(formcollection collection)
    {
        person person = new person();
 updatemodel(person, collection);
        //...
    }
    //...
}

public class person
{
    public int id { get; set; }
    public string name { get; set; }

}需要进行 trim 的大致有以下三种:

action 中的字符串参数,如 query 方法中的 name 参数。
action 中的复杂类型参数的字符串属性,如 create 方法中的 person 的 name 属性。
action 中显式绑定的复杂类型的字符串属性,如 create2 方法中的 person 的 name 属性。

如果 model 更复杂:

public class person
{
    public int id { get; set; }
    public string name { get; set; }
    public string[] hobbies { get; set; }
    public person father { get; set; }

}   还需要对 hobbies 和 father.name 进行处理…

但在 mvc 中可以通过 modelbinder 来轻松解决。

使用 modelbinder 来解决 trim 问题
使用 modelbinder 来解决 trim 问题,有 n 多种方式,本文介绍最简单的一种,只需要以下两步:

1. 创建一个有 trim 功能的 modelbinder(仅用于 string 类型):

public class stringtrimmodelbinder : defaultmodelbinder
{
    public override object bindmodel(controllercontext controllercontext, modelbindingcontext bindingcontext)
    {
        var value = base.bindmodel(controllercontext, bindingcontext);
        if (value is string) return (value as string).trim();
        return value;
    }

}简单吧,就三行代码(其实还可以再精简)。

2. 在 global.asax 中为 string 类型指定这个 modelbinder:

public class mvcapplication : system.web.httpapplication
{
    protected void application_start()
    {
        modelbinders.binders.add(typeof(string), new stringtrimmodelbinder());
        //...
    }
    //...


}根据 mvc 的绑定机制,所有的字符串绑定都将会使用 stringtrimmodelbinder。

也就是说,我们前面应用场景中提到的各种类型字符串都可以自动 trim 了,包括 person.name、 person.hobbies 和 person.father.name。

本文来源:http://www.gdgbn.com/jiaocheng/28638/