ASP.NET MVC - NHibernate - DropDownLists
i am just getting started with ASP.NET MVC and i'm using NHibernate for my data context. I have kept the foreign key fields in my entity classes so that it could hopefully making working with drop down lists easier but this is not 开发者_运维问答the case.
Here is my post back action:
var user = userRepository.GetById(id);
if (!TryUpdateModel(user, "User", new[] { "UserName", "RoleID" }))
return View(user);
// Update the role
user.Role = roleRepository.GetById(user.RoleID);
This allows me to put my validation logic on the User.RoleID property.
Everything works fine until it saves it. Here's my user and mapping class:
public virtual int UserID { get; set; }
[Required(ErrorMessage = "Username is required")]
public virtual string UserName { get; set; }
[Required(ErrorMessage = "Role is required")]
public virtual int RoleID { get; set; }
public virtual Role Role { get; set; }
public UserMap()
{
Table("Users");
Id(x => x.UserID);
Map(x => x.UserName);
Map(x => x.RoleID);
References(x => x.Role, "RoleID");
}
However this throws back an error when it trys to commit the changes. I tried removing Map(x => x.RoleID); from the above mapping and the insert went through successfully but then the data was not populated when displaying the user.
My preferred solution would be to remove the RoleID property from the User entity (as recommended by NHibernate) but then i would have to handle my validation logic myself.
I'd appreciate it if someone could help. Thanks
i've found the best way to do this is to say the following:
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(FormCollection collection)
{
var user = new User();
if (!TryUpdateModel(user, new[] { "UserName", "Role" }))
return View(user);
...
}
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Edit(int id, FormCollection collection, string returnUrl)
{
var user = userRepository.GetById(id);
user.Role = new Role(); // Needed to prevent another issue when saving
if (!TryUpdateModel(user, new[] { "UserName", "Role" }))
return View(user);
...
}
For now i'm relatively happy with my hacky solution but if someone knows how i can get rid of the user.Role = new Role(); in the Edit action i'd appreciate it if they could share. Thanks
btw if you are returning multiple data to to the view when your validation fails and you need to do a get (eg to retrieve the Roles). Then you need to Rollback the changes you've made in the nhibernate transaction to prevent another issue. Hope this saves someone some time :).
精彩评论