Mono提供很多组件可以方便的处理页面:可以自动将后台的值填充到页面,可以自动进行Javascript验证,可以自动在后台验证等。这些功能都是比较实用的,可以减少很多开发
FormHelper是用来对应html页面中Form内的tag的,可以自动填充textbox等
ValidationHelper可以帮助我们在前台利用Javascript验证
Castle.Components.Validator组件可以在后台对页面输入值进行验证
一、自动填充页面
普通填充:
HomeController:
  public void Fill1()
        public void Fill1()
 {
        {
 PropertyBag.Add("id", "1");
            PropertyBag.Add("id", "1");
 PropertyBag.Add("name", "GSpring");
            PropertyBag.Add("name", "GSpring");
 PropertyBag.Add("sex", "1");
            PropertyBag.Add("sex", "1");
 }  Fill1.vm:
        }  Fill1.vm:
  <form >
<form >
 id:$FormHelper.TextField("id")<br />
id:$FormHelper.TextField("id")<br />
 name:$FormHelper.TextField("name")<br />
name:$FormHelper.TextField("name")<br />
 sex
sex
 male:$FormHelper.RadioField("sex", "1")
 male:$FormHelper.RadioField("sex", "1")
 female:$FormHelper.RadioField("sex", "0")
 female:$FormHelper.RadioField("sex", "0")
 </form>  当我们执行http://****/home/Fill1.rails时会自动将对应的值绑定到页面中去,页面结果为:
</form>  当我们执行http://****/home/Fill1.rails时会自动将对应的值绑定到页面中去,页面结果为:

我这里只是实验了常用的textbox和radiobutton,其他的也是同样处理的
高级填充:
  public void Index()
public void Index()
 {
{
 PropertyBag.Add("list", new string[]
    PropertyBag.Add("list", new string[] 
 {
    {
 "value 1", "value 2"
        "value 1", "value 2"
 } );
    } );

 PropertyBag.Add("contacts", new Contact[]
    PropertyBag.Add("contacts", new Contact[] 
 {
    { 
 new Contact("john", "address 1", "phone number 1"),
        new Contact("john", "address 1", "phone number 1"),
 new Contact("mary", "address 2", "phone number 2")
        new Contact("mary", "address 2", "phone number 2")
 } );
    } );
 }  Vm代码:
}  Vm代码:
  <form action="Save.rails" method="post">
<form action="Save.rails" method="post">

 $FormHelper.TextField("list[0]")
$FormHelper.TextField("list[0]")
 $FormHelper.TextField("list[1]")
$FormHelper.TextField("list[1]")

 $FormHelper.TextField("contacts[0].name")
$FormHelper.TextField("contacts[0].name")
 $FormHelper.TextField("contacts[0].address")
$FormHelper.TextField("contacts[0].address")
 $FormHelper.TextField("contacts[0].phone")
$FormHelper.TextField("contacts[0].phone")

 $FormHelper.TextField("contacts[1].name")
$FormHelper.TextField("contacts[1].name")
 $FormHelper.TextField("contacts[1].address")
$FormHelper.TextField("contacts[1].address")
 $FormHelper.TextField("contacts[1].phone")
$FormHelper.TextField("contacts[1].phone")
 </form>  可以自动将对象、数组中对应的值填充到页面上去
</form>  可以自动将对象、数组中对应的值填充到页面上去
二、前台验证
1、 只能输入数字的限制
只需要在Vm中写:
$FormHelper.InstallScripts()
$FormHelper.NumberField("age")
$FormHelper.NumberField("amount", "%{exceptions='32',forbid='48,49'}")
第一句是注册脚本,第二句是生成一个textbox,并且只能输入数字
第三句是生成一个textbox,并且只能输入数字,同时可以输入code=32的字符,同时不能输入code=48或49的字符
2、ValidationHelper验证
功能很强大,我这里只是列出一些简单的使用,使用这种方式时几乎不需要后台代码,只需要在vm文件中定义就可以了:
  <html>
<html>
 <head>
    <head>
 <title>Validation Test</title>
        <title>Validation Test</title>
 $ValidationHelper.InstallScripts()
        $ValidationHelper.InstallScripts()
 $ValidationHelper.SetSubmitOptions(true, true, false, 0)
        $ValidationHelper.SetSubmitOptions(true, true, false, 0)
 </head>
    </head>
 <body>
    <body>
 <form method="post" id="demoForm" onsubmit="$ValidationHelper.GetValidationTriggerFunction()">
        <form method="post" id="demoForm" onsubmit="$ValidationHelper.GetValidationTriggerFunction()">
 姓名:<input type="text" name="Name" id="Name" displayName="姓名" validators="blank" /><br />
                    姓名:<input type="text" name="Name" id="Name" displayName="姓名" validators="blank" /><br />
 密码:<input type="password" name="Password" id="Password" validators="length|6" /><br />
                    密码:<input type="password" name="Password" id="Password" validators="length|6" /><br />
 邮件:<input type="text" name="Email" id="Email" validators="email|3" /><br />
                    邮件:<input type="text" name="Email" id="Email" validators="email|3" /><br />
 确认邮件:<input type="text" name="Email_Confirm" id="Email_Confirm" validators="equalto|Email" /><br />
                    确认邮件:<input type="text" name="Email_Confirm" id="Email_Confirm" validators="equalto|Email" /><br />
 <input type="submit" name="Submit" value="测试" />
                <input type="submit" name="Submit" value="测试" />
 </form>
        </form>
 </body>
    </body>
 </html>  开始的$ValidationHelper.InstallScripts()和$ValidationHelper.SetSubmitOptions(true, true, false, 0)两句话是注册脚本的,不能少
</html>  开始的$ValidationHelper.InstallScripts()和$ValidationHelper.SetSubmitOptions(true, true, false, 0)两句话是注册脚本的,不能少
然后主要就是validators属性设置的值了,比如:blank(不能为空)、length|6(六位长度)、email(邮件类型)等
在这个例子中,当什么也不输,直接点测试时,会弹出一个对话框报错:Please enter 姓名
这里显示的都是英文的报错信息,如果需要使用中文报错,可以使用以下方法:
(由于目前MonoRail没有提供简体中文的报错,需要我们自己生成)
复制MonoRail\Castle.MonoRail.Framework\Controllers目录下的ValidationLang.resx文件,改名为ValidationLang.zh-cn.resx,然后将此文件中对应的英文提示改为中文,比如:
  fvalidate.i18n =
            fvalidate.i18n =
 {
            {
 //    Validation errors
                //    Validation errors
 errors:
                errors:
 {
                {
 blank:        [
                    blank:        [
 ["请输入:", 0]
                        ["请输入:", 0]
 ],  将框架项目重新编译
                        ],  将框架项目重新编译
然后将vm中的第四条语句改成:
$ValidationHelper.InstallScripts("zh-cn")
这样当再次照上面的步骤执行时会弹出一个对话框报错:请输入:姓名
三、Castle.Components.Validator后台验证使用
ValidatorController.cs代码:
  public class User
    public class User
 {
    {
 private int id;
        private int id;
 private string name, email, password, confirmation;
        private string name, email, password, confirmation;

 public User()
        public User()
 {
        {
 }
        }
 public User(string name, string email)
        public User(string name, string email)
 {
        {
 this.name = name;
            this.name = name;
 this.email = email;
            this.email = email;
 }
        }

 public int Id
        public int Id
 {
        {
 get { return id; }
            get { return id; }
 set { id = value; }
            set { id = value; }
 }
        }

 [ValidateNonEmpty]
        [ValidateNonEmpty]
 public string Name
        public string Name
 {
        {
 get { return name; }
            get { return name; }
 set { name = value; }
            set { name = value; }
 }
        }

 [ValidateNonEmpty, ValidateEmail]
        [ValidateNonEmpty, ValidateEmail]
 public string Email
        public string Email
 {
        {
 get { return email; }
            get { return email; }
 set { email = value; }
            set { email = value; }
 }
        }

 [ValidateNonEmpty]
        [ValidateNonEmpty]
 public string Password
        public string Password
 {
        {
 get { return password; }
            get { return password; }
 set { password = value; }
            set { password = value; }
 }
        }

 [ValidateSameAs("Password")]
        [ValidateSameAs("Password")]
 public string Confirmation
        public string Confirmation
 {
        {
 get { return confirmation; }
            get { return confirmation; }
 set { confirmation = value; }
            set { confirmation = value; }
 }
        }
 }
    }

 public class ValidatorController : SmartDispatcherController
    public class ValidatorController : SmartDispatcherController
 {
    {
 public ValidatorController()
        public ValidatorController()
 {
        {
 }
        }

 public void Index()
        public void Index()
 {
        {
 }
        }
 public void Test([DataBind("user", Validate = true)] User user)
        public void Test([DataBind("user", Validate = true)] User user)
 {
        {
 if (HasValidationError(user))
            if (HasValidationError(user))
 {
            {
 Flash["user"] = user;
                Flash["user"] = user;
 Flash["summary"] = GetErrorSummary(user);
                Flash["summary"] = GetErrorSummary(user);
 RedirectToReferrer();
                RedirectToReferrer();
 }
            }
 else
            else
 {
            {
 //其他操作
                //其他操作
 CancelView();
                CancelView();
 }
            }
 }
        }
 }  最主要的就是User中每个字段上定义的属性,比如ValidateNonEmpty(不能为空)、ValidateEmail(邮件格式)、ValidateSameAs(判断是否相同)、ValidateLeng(长度判断)、ValidateDate(日期判断)等
    }  最主要的就是User中每个字段上定义的属性,比如ValidateNonEmpty(不能为空)、ValidateEmail(邮件格式)、ValidateSameAs(判断是否相同)、ValidateLeng(长度判断)、ValidateDate(日期判断)等
index.vm:
  <html>
<html>
 <body>
<body>
 $FormHelper.FormTag("%{action='Test', immediate='true', useLabels='true'}")
$FormHelper.FormTag("%{action='Test', immediate='true', useLabels='true'}")

 #if($summary)
#if($summary)
 <p>
<p>
 <div>
    <div>
 发生以下错误:
    发生以下错误:
 </div>
    </div>
 #foreach($propName in $summary.InvalidProperties)
    #foreach($propName in $summary.InvalidProperties)
 $propName: #foreach($msg in $summary.GetErrorsForProperty($propName)) $msg #end <br/>
    $propName: #foreach($msg in $summary.GetErrorsForProperty($propName)) $msg #end <br/>
 #end
    #end
 </p>
</p>
 #end
#end
 姓名:$FormHelper.TextField("user.name")<br />
    姓名:$FormHelper.TextField("user.name")<br />
 邮件:$FormHelper.TextField("user.email")<br />
    邮件:$FormHelper.TextField("user.email")<br />
 密码:$FormHelper.PasswordField("user.password")<br />
    密码:$FormHelper.PasswordField("user.password")<br />
 确认密码:$Form.PasswordField("user.confirmation")<br />
    确认密码:$Form.PasswordField("user.confirmation")<br />
 <input type="submit" value="确认" />
<input type="submit" value="确认" />
 $FormHelper.EndFormTag()
$FormHelper.EndFormTag()
 </body>
</body>
 </html>  当浏览 http://localhost:***/validator/index.rails 在什么也不输的情况下直接点确认,会报错:
</html>  当浏览 http://localhost:***/validator/index.rails 在什么也不输的情况下直接点确认,会报错:

这样,我们几乎一句检查的代码都没写,就可以达到检查的效果了
当然,默认的报错信息是英文的,我们可以修改如下定义:
  [ValidateNonEmpty("不能为空", FriendlyName="姓名")]
        [ValidateNonEmpty("不能为空", FriendlyName="姓名")]
 public string Name
        public string Name
 {
        {
 get { return name; }
            get { return name; }
 set { name = value; }
            set { name = value; }
 }  那么在姓名列没输入时会报错:姓名: 不能为空
        }  那么在姓名列没输入时会报错:姓名: 不能为空
 
FormHelper是用来对应html页面中Form内的tag的,可以自动填充textbox等
ValidationHelper可以帮助我们在前台利用Javascript验证
Castle.Components.Validator组件可以在后台对页面输入值进行验证
一、自动填充页面
普通填充:
HomeController:
 public void Fill1()
        public void Fill1() {
        { PropertyBag.Add("id", "1");
            PropertyBag.Add("id", "1"); PropertyBag.Add("name", "GSpring");
            PropertyBag.Add("name", "GSpring"); PropertyBag.Add("sex", "1");
            PropertyBag.Add("sex", "1"); }
        }  <form >
<form > id:$FormHelper.TextField("id")<br />
id:$FormHelper.TextField("id")<br /> name:$FormHelper.TextField("name")<br />
name:$FormHelper.TextField("name")<br /> sex
sex male:$FormHelper.RadioField("sex", "1")
 male:$FormHelper.RadioField("sex", "1") female:$FormHelper.RadioField("sex", "0")
 female:$FormHelper.RadioField("sex", "0") </form>
</form> 
我这里只是实验了常用的textbox和radiobutton,其他的也是同样处理的
高级填充:
 public void Index()
public void Index() {
{ PropertyBag.Add("list", new string[]
    PropertyBag.Add("list", new string[]  {
    { "value 1", "value 2"
        "value 1", "value 2" } );
    } );
 PropertyBag.Add("contacts", new Contact[]
    PropertyBag.Add("contacts", new Contact[]  {
    {  new Contact("john", "address 1", "phone number 1"),
        new Contact("john", "address 1", "phone number 1"), new Contact("mary", "address 2", "phone number 2")
        new Contact("mary", "address 2", "phone number 2") } );
    } ); }
}  <form action="Save.rails" method="post">
<form action="Save.rails" method="post">
 $FormHelper.TextField("list[0]")
$FormHelper.TextField("list[0]") $FormHelper.TextField("list[1]")
$FormHelper.TextField("list[1]")
 $FormHelper.TextField("contacts[0].name")
$FormHelper.TextField("contacts[0].name") $FormHelper.TextField("contacts[0].address")
$FormHelper.TextField("contacts[0].address") $FormHelper.TextField("contacts[0].phone")
$FormHelper.TextField("contacts[0].phone")
 $FormHelper.TextField("contacts[1].name")
$FormHelper.TextField("contacts[1].name") $FormHelper.TextField("contacts[1].address")
$FormHelper.TextField("contacts[1].address") $FormHelper.TextField("contacts[1].phone")
$FormHelper.TextField("contacts[1].phone") </form>
</form> 二、前台验证
1、 只能输入数字的限制
只需要在Vm中写:
$FormHelper.InstallScripts()
$FormHelper.NumberField("age")
$FormHelper.NumberField("amount", "%{exceptions='32',forbid='48,49'}")
第一句是注册脚本,第二句是生成一个textbox,并且只能输入数字
第三句是生成一个textbox,并且只能输入数字,同时可以输入code=32的字符,同时不能输入code=48或49的字符
2、ValidationHelper验证
功能很强大,我这里只是列出一些简单的使用,使用这种方式时几乎不需要后台代码,只需要在vm文件中定义就可以了:
 <html>
<html> <head>
    <head> <title>Validation Test</title>
        <title>Validation Test</title> $ValidationHelper.InstallScripts()
        $ValidationHelper.InstallScripts() $ValidationHelper.SetSubmitOptions(true, true, false, 0)
        $ValidationHelper.SetSubmitOptions(true, true, false, 0) </head>
    </head> <body>
    <body> <form method="post" id="demoForm" onsubmit="$ValidationHelper.GetValidationTriggerFunction()">
        <form method="post" id="demoForm" onsubmit="$ValidationHelper.GetValidationTriggerFunction()"> 姓名:<input type="text" name="Name" id="Name" displayName="姓名" validators="blank" /><br />
                    姓名:<input type="text" name="Name" id="Name" displayName="姓名" validators="blank" /><br /> 密码:<input type="password" name="Password" id="Password" validators="length|6" /><br />
                    密码:<input type="password" name="Password" id="Password" validators="length|6" /><br /> 邮件:<input type="text" name="Email" id="Email" validators="email|3" /><br />
                    邮件:<input type="text" name="Email" id="Email" validators="email|3" /><br /> 确认邮件:<input type="text" name="Email_Confirm" id="Email_Confirm" validators="equalto|Email" /><br />
                    确认邮件:<input type="text" name="Email_Confirm" id="Email_Confirm" validators="equalto|Email" /><br /> <input type="submit" name="Submit" value="测试" />
                <input type="submit" name="Submit" value="测试" /> </form>
        </form> </body>
    </body> </html>
</html> 然后主要就是validators属性设置的值了,比如:blank(不能为空)、length|6(六位长度)、email(邮件类型)等
在这个例子中,当什么也不输,直接点测试时,会弹出一个对话框报错:Please enter 姓名
这里显示的都是英文的报错信息,如果需要使用中文报错,可以使用以下方法:
(由于目前MonoRail没有提供简体中文的报错,需要我们自己生成)
复制MonoRail\Castle.MonoRail.Framework\Controllers目录下的ValidationLang.resx文件,改名为ValidationLang.zh-cn.resx,然后将此文件中对应的英文提示改为中文,比如:
 fvalidate.i18n =
            fvalidate.i18n = {
            { //    Validation errors
                //    Validation errors errors:
                errors: {
                { blank:        [
                    blank:        [ ["请输入:", 0]
                        ["请输入:", 0] ],
                        ], 然后将vm中的第四条语句改成:
$ValidationHelper.InstallScripts("zh-cn")
这样当再次照上面的步骤执行时会弹出一个对话框报错:请输入:姓名
三、Castle.Components.Validator后台验证使用
ValidatorController.cs代码:
 public class User
    public class User {
    { private int id;
        private int id; private string name, email, password, confirmation;
        private string name, email, password, confirmation;
 public User()
        public User() {
        { }
        } public User(string name, string email)
        public User(string name, string email) {
        { this.name = name;
            this.name = name; this.email = email;
            this.email = email; }
        }
 public int Id
        public int Id {
        { get { return id; }
            get { return id; } set { id = value; }
            set { id = value; } }
        }
 [ValidateNonEmpty]
        [ValidateNonEmpty] public string Name
        public string Name {
        { get { return name; }
            get { return name; } set { name = value; }
            set { name = value; } }
        }
 [ValidateNonEmpty, ValidateEmail]
        [ValidateNonEmpty, ValidateEmail] public string Email
        public string Email {
        { get { return email; }
            get { return email; } set { email = value; }
            set { email = value; } }
        }
 [ValidateNonEmpty]
        [ValidateNonEmpty] public string Password
        public string Password {
        { get { return password; }
            get { return password; } set { password = value; }
            set { password = value; } }
        }
 [ValidateSameAs("Password")]
        [ValidateSameAs("Password")] public string Confirmation
        public string Confirmation {
        { get { return confirmation; }
            get { return confirmation; } set { confirmation = value; }
            set { confirmation = value; } }
        } }
    }
 public class ValidatorController : SmartDispatcherController
    public class ValidatorController : SmartDispatcherController {
    { public ValidatorController()
        public ValidatorController() {
        { }
        }
 public void Index()
        public void Index() {
        { }
        } public void Test([DataBind("user", Validate = true)] User user)
        public void Test([DataBind("user", Validate = true)] User user) {
        { if (HasValidationError(user))
            if (HasValidationError(user)) {
            { Flash["user"] = user;
                Flash["user"] = user; Flash["summary"] = GetErrorSummary(user);
                Flash["summary"] = GetErrorSummary(user); RedirectToReferrer();
                RedirectToReferrer(); }
            } else
            else {
            { //其他操作
                //其他操作 CancelView();
                CancelView(); }
            } }
        } }
    } index.vm:
 <html>
<html> <body>
<body> $FormHelper.FormTag("%{action='Test', immediate='true', useLabels='true'}")
$FormHelper.FormTag("%{action='Test', immediate='true', useLabels='true'}")
 #if($summary)
#if($summary) <p>
<p> <div>
    <div> 发生以下错误:
    发生以下错误: </div>
    </div> #foreach($propName in $summary.InvalidProperties)
    #foreach($propName in $summary.InvalidProperties) $propName: #foreach($msg in $summary.GetErrorsForProperty($propName)) $msg #end <br/>
    $propName: #foreach($msg in $summary.GetErrorsForProperty($propName)) $msg #end <br/> #end
    #end </p>
</p> #end
#end 姓名:$FormHelper.TextField("user.name")<br />
    姓名:$FormHelper.TextField("user.name")<br /> 邮件:$FormHelper.TextField("user.email")<br />
    邮件:$FormHelper.TextField("user.email")<br /> 密码:$FormHelper.PasswordField("user.password")<br />
    密码:$FormHelper.PasswordField("user.password")<br /> 确认密码:$Form.PasswordField("user.confirmation")<br />
    确认密码:$Form.PasswordField("user.confirmation")<br /> <input type="submit" value="确认" />
<input type="submit" value="确认" /> $FormHelper.EndFormTag()
$FormHelper.EndFormTag() </body>
</body> </html>
</html> 
这样,我们几乎一句检查的代码都没写,就可以达到检查的效果了
当然,默认的报错信息是英文的,我们可以修改如下定义:
 [ValidateNonEmpty("不能为空", FriendlyName="姓名")]
        [ValidateNonEmpty("不能为空", FriendlyName="姓名")] public string Name
        public string Name {
        { get { return name; }
            get { return name; } set { name = value; }
            set { name = value; } }
        } 其实User类的定义就相当于一张表的Model,在Monorail中把Model定义好,就可以达到验证的功能了
本文转自永春博客园博客,原文链接:http://www.cnblogs.com/firstyi/archive/2007/10/31/944282.html,如需转载请自行联系原作者