【发布时间】:2012-04-10 20:57:54
【问题描述】:
我正在开发一个 ASP.NET MVC 3 应用程序,我首先使用实体框架代码来创建我的应用程序的类,并且我还有一个存储库来对其执行操作,保持 DBContext 的清洁和 DBEntities 定义。
我怀疑视图的渲染和编辑模型的保存方式。
如果我有代表存储在我的数据库中的用户的这个实体:
//Entity:
public class User
{
[Key]
public int IdUser { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
我想显示一个包含 FirstName、LastName、Email 和 NewPassword、ConfirmPasword 和 CurrentPassword 的视图,以便让用户更改他的数据,输入 CurrentPassword 以确认更改,所以我怀疑,像 ConfirmPasword 这样的字段和 CurrentPassword 不在我的实体中,所以我需要为此视图创建一个新模型,并将我想要的信息从我的新模型复制到我的数据库实体以保存它?喜欢:
public class UpdateUserModel
{
[Required]
[Display(Name = "Name")]
public string FirstName{ get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName{ get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Not valid email")]
public string Email { get; set; }
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPasword{ get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm the New Pasword")]
[Compare("NewPasword", ErrorMessage = "Password doesn´t mach.")]
public string ConfirmPasword{ get; set; }
[Required(ErrorMessage = "Need to specify the current password to save changes")]
[DataType(DataType.Password)]
[Display(Name = "Current Password")]
public string CurrentPassword { get; set; }
}
在我制作的控制器中:
public ActionResult UpdateUser(UpdateUserModel model)
{
User u = (User)Membership.GetUser();
u.FirstName = model.FirstName;
u.LastName = model.LastName;
u.Email = model.Email;
if (!String.IsNullOrEmpty(model.NewPassword))
{
u.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(model.NewPassword.Trim(), "md5");
}
repository.UpdateUser(u);
return View();
}
有这样的控制器可以做到这一点:
public ActionResult UpdateUser(User u)
{
repository.UpdateUser(u);
return View();
}
因为如果我有这个,我如何添加字段,如 ConfirmPassword 或 CurrentPassword 以便对此特定视图进行验证。
【问题讨论】:
标签: asp.net-mvc entity-framework model-view-controller design-patterns