数据注解MVC3必需属性 [英] Data annotations MVC3 Required attribute

查看:106
本文介绍了数据注解MVC3必需属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型(用户)下面,我用它来添加新用户,更新现有用户。
当我添加新用户它需要输入用户名和密码,当我更新它是必需的,因为它是不允许更改密码只输入用户名。这里的问题是,加入是因为我同时输入名和密码值,所以ModelState.IsValid返回true,但更新一个用户在没有输入密码的新用户一切工作正常,所以它总是空值是什么让ModelState.IsValid返回false所有的时间。
有没有使用相同的模型,即使在添加查看密码是必需的,在更新视图它不是一个办法吗?
请,有什么建​​议?

 公共类用户{        公众诠释ID {搞定;组; }        [显示(NAME =诺姆做Usuário)]
        [必需(的ErrorMessage =DigiteØ诺姆做Usuário。)
        公共字符串名称{;组; }        [显示(NAME =Senha)]
        [必需(的ErrorMessage =Digite一个Senha。)
        公共字符串密码{搞定;组; }    }公众的ActionResult的Add()
        {
            返回查看();
        }      [HttpPost]
            公众的ActionResult添加(用户用户)
            {
                UsuariosViewModel视图模型=新UsuariosViewModel();
                如果(ModelState.IsValid)
                {
                    viewModel.Msg =新AdmUsuarios()CadastraUsuario(用户)。
                }
                返回视图(视图模型);
            }    公众的ActionResult更新(INT ID)
            {
                UsuariosViewModel视图模型=新UsuariosViewModel();            使用(VAR的DataContext =新DBEntities())
            {
                存储库<使用者>库=新库<使用者>(DataContext的);
                viewModel.User = repository.GetById(ID);
            }                返回视图(视图模型);
            }        [HttpPost]
        公众的ActionResult更新(用户用户,INT ID)
        {
            UsuariosViewModel视图模型=新UsuariosViewModel();            如果(ModelState.IsValid)
            {
                viewModel.Msg =新AdmUsuarios()AlteraUsuario(用户ID)。
            }
            返回查看();
        }


解决方案

您应该使用视图模型。

您数据的注释,然后将在视图模型属于被传递到视图

 公共类CreateViewModel
{
  公众诠释ID {搞定;组; }  [显示(NAME =诺姆做Usuário)]
  [必需(的ErrorMessage =DigiteØ诺姆做Usuário。)
  公共字符串名称{;组; }  [显示(NAME =Senha)]
  [必需(的ErrorMessage =Digite一个Senha。)
  公共字符串密码{搞定;组; }
}

和进行编辑

 公共类EditViewModel
    {
      公众诠释ID {搞定;组; }      [显示(NAME =诺姆做Usuário)]
      [必需(的ErrorMessage =DigiteØ诺姆做Usuário。)
      公共字符串名称{;组; }      //也许你不需要密码在所有的编辑视图
    }

通过这些类视图(S),而不是你的域模型(用户),那么,在控制器,地图视图模型属性回模型前坚持到数据源。

I have the Model (User) below, I use it to add new users and to update existing users. When I'm adding a new user it's required to enter the user name and the password, and when I'm updating it's required to enter only the user name because it's not allowed to change the password. Here is the problem, adding a new user everything works ok because I enter both name and password values so ModelState.IsValid returns true, but when updating an user there is no input to the password, so it always have the null value what makes the ModelState.IsValid returns false all the time. Is there a way to use the same model even if in the Add View the password is required and in the Update View it's not? please, any suggestions?

     public class User {

        public int ID { get; set; }

        [Display(Name = "Nome do Usuário")]
        [Required(ErrorMessage = "Digite o Nome do Usuário.")]
        public string name { get; set; }

        [Display(Name = "Senha")]
        [Required(ErrorMessage = "Digite a Senha.")]
        public string password { get; set; }

    }



public ActionResult Add()
        {
            return View();
        }

      [HttpPost]
            public ActionResult Add(User user)
            {
                UsuariosViewModel viewModel = new UsuariosViewModel();


                if (ModelState.IsValid)
                {
                    viewModel.Msg = new AdmUsuarios().CadastraUsuario(user);
                }
                return View(viewModel);
            }



    public ActionResult Update(int id)
            {
                UsuariosViewModel viewModel = new UsuariosViewModel();

            using (var dataContext = new DBEntities()) 
            {
                Repository<User> repository = new Repository<User>(dataContext);
                viewModel.User = repository.GetById(id);
            }

                return View(viewModel);
            }

        [HttpPost]
        public ActionResult Update(User user, int id)
        {          
            UsuariosViewModel viewModel = new UsuariosViewModel();

            if (ModelState.IsValid)
            {
                viewModel.Msg = new AdmUsuarios().AlteraUsuario(user, id);
            }
            return View();
        }

解决方案

You should use view models.

Your data annotations would then belong on the view model being passed to the view

public class CreateViewModel
{
  public int ID { get; set; }

  [Display(Name = "Nome do Usuário")]
  [Required(ErrorMessage = "Digite o Nome do Usuário.")]
  public string name { get; set; }

  [Display(Name = "Senha")]
  [Required(ErrorMessage = "Digite a Senha.")]
  public string password { get; set; }
}

and for edit

 public class EditViewModel
    {
      public int ID { get; set; }

      [Display(Name = "Nome do Usuário")]
      [Required(ErrorMessage = "Digite o Nome do Usuário.")]
      public string name { get; set; }

      //perhaps you don't need the password at all in the edit view
    }

Pass these classes to your view(s), not your domain model(User), then, in the controller, map the view model properties back to the model before persisting to your data source.

这篇关于数据注解MVC3必需属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆