【www.gdgbn.com--Action】

str.trim()是.net的用法
trim(str)是vb的用法.这种用法不能用于c#,但上面那种可以用于c#

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

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

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

创建一个有 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;
    }
}

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

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

本文来源:http://www.gdgbn.com/flash/28645/