2011-12-06 113 views
0

MVC 3中的“远程”注释允许您调用“动作”为您执行属性数据验证。这很漂亮!或者...是真的吗?MVC 3 - 带注释的表单验证

问题:下面的“远程”注释(见注释)在客户端调用代码!我的角色类在模型中。我喜欢“远程”,因为我不需要编写自定义验证器。

我应该使用对象视图模型模式并将属性“Role.Name”重复在那里吗?那会奏效。然后是另一个问题:我如何才能真正避免DRY原则(不要重复自己)?在对象视图中使用带注释的属性是否有效,然后在模型中使用相同的属性?我的意思是,分离担忧是否太多了?

我只是试图设计这个权利,并应用正确的设计原则,所以当这个网站增长代码明智时,我不会被烧毁。

这样做的最好方法是什么?

namespace StartWeb.Model.ObjectModel 
{ 
public class Role //this class is in the Model (see namespace) and it needs to be "client agnostic” 
    { 

     //Then, this annotation is NOT client agnostic, it calls a controller: 
     [Remote("ValidateRoleName", "Role", AdditionalFields="InitialRoleName", ErrorMessage = "Role Name already exists")] 
     public string Name { get; set; } 

这是RoleController行动验证码(在“客户端”):

[HttpGet] 
    [OutputCache(Location = OutputCacheLocation.None, NoStore = true)] 
    public JsonResult ValidateRoleName(string name, string initialRoleName) 
    { 
     bool isValid = true; 
     if (name != initialRoleName) isValid = !(new SecurityFacade().IsRoleNameExist(name));   
     return Json(isValid, JsonRequestBehavior.AllowGet); 
    } 

回答