MVC 3 - 带注释的表单验证

时间:2011-12-06 15:23:01

标签: asp.net-mvc

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);
    }

1 个答案:

答案 0 :(得分:0)

经过进一步的研究,我找到了这个开源工具,它可以为你从不同层映射实体做繁重的工作:

Automapper tool between domain model and view models

相关问题