如何在 ASP.NET MVC 中将复杂的 ViewModel 传递到服务层?
假设我有用于用户注册的 RegisterModel 和一些实现 IUserService 的 UserService
public interface IUserService
{
User CreateUser(User newUser);
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// ... logic for newuser
User user = _userService.CreateUser(newuser);
_authenticationService.SetAuthenticatedUser(user);
return RedirectToRoute("Homepage");
}
return View(model);
}
考虑到 RegisterModel 可能非常复杂,将 RegisterModel 映射到 User 对象的逻辑应该在哪里
Say I have RegisterModel for user registration and some UserService that implementing IUserService
public interface IUserService
{
User CreateUser(User newUser);
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// ... logic for newuser
User user = _userService.CreateUser(newuser);
_authenticationService.SetAuthenticatedUser(user);
return RedirectToRoute("Homepage");
}
return View(model);
}
Given that RegisterModel might be very complex, where is the logic should go for mapping RegisterModel to User object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您永远不会将视图模型传递给服务。服务甚至不知道您可能在 GUI (ASP.NET MVC) 层中定义的视图模型的存在。服务与域模型一起使用。就我个人而言,我使用 AutoMapper 在视图模型和模型之间进行映射,反之亦然,因此此逻辑进入映射层。
You never pass a view model to a service. A service doesn't even know about the existence of a view model that you might have defined in your GUI (ASP.NET MVC) tier. A service works with domain models. Personally I use AutoMapper to map between view models and models and vice versa, so this logic goes into the mapping layer.