您刚考虑在控制器中映射和绑定我的实体。 我应该如何正确绑定模型中的实体,以便我可以使用modelstate
我正在使用MenuItemModel创建新的MenuItem。
public class MenuItemModel
{
public List<SelectListItem> Menus { get; set; }
public MenuItem MenuItem { get; set; }
}
我的MenuItem类定义如下:
public class MenuItem:Entity
{
public virtual int MenuItemId { get; set; }
public virtual Menu Menu { get; set; }
[Required]
public virtual string Name { get; set; }
public virtual int ItemOrder { get; set; }
public virtual string ExternalUrl { get; set; }
public virtual DateTime Created { get; set; }
public virtual bool Deleted { get; set; }
public virtual DateTime? DisplayUntil { get; set; }
public virtual User Author { get; set; }
}
现在当我在控制器中绑定我的实体时。
//
// POST: /Administrator/MenuItem/Create
[HttpPost]
public ActionResult Create(MenuItem menuItem)
{
if (ModelState.IsValid)
{
// do saving logic
menuItem.Created = DateTime.Now;
menuItem.Author = this._userProvider.GetCurrentUser();
menuItem.Menu = _menuRepository.Load(menuItem.Menu.MenuId);
}
//restore
MenuItemModel menuItemModel = new MenuItemModel();
menuItemModel.MenuItem = menuItem;
menuItemModel.Menus =
this._menuRepository.All.Select(x => new SelectListItem() { Text = x.Name, Value = x.MenuId.ToString() }).ToList();
return View(menuItemModel);
}
唯一的问题是我的验证不仅适用于MenuItem,还适用于菜单,用户。
如何将此验证设置为仅接受MenuItem实体的验证?
PS我知道我可以进入模型状态项目并只查找我需要的实体并检查它们是否有效但我相信会有更好的方法来做到这一点......
任何想法都表示赞赏。
答案 0 :(得分:2)
如何将此验证设置为仅接受MenuItem实体的验证?
您应该使用一个视图模型,该模型仅包含在控制器操作中需要验证的属性(通常是表单中包含并由用户输入的属性)。视图模型是专门为给定视图的要求而设计的类。控制器操作永远不应传递/从视图中获取域模型。控制器操作应始终将视图模型传递给视图或从视图中获取视图模型。例如:
public class MenuItemViewModel
{
public int MenuItemId { get; set; }
[Required]
public string Name { get; set; }
... put any properties that are contained on the form with their
respective validation
}
然后让你的POST控制器操作将此视图模型作为参数:
[HttpPost]
public ActionResult Create(MenuItemViewModel viewModel)
{
if (!ModelState.IsValid)
{
// there were some validation errors => redisplay the view
// so that the user can fix them
return View(viewModel);
}
// at this stage validation went fine
// TODO: map the view model back to a domain model
// (MenutItem or whatever you are willing to update)
// I would recommend you AutoMapper for this task: http://automapper.codeplex.com/
// TODO: once you get the domain model pass it to a service layer
// method in order to perform the necessary business operation with it
// (in your case creating a menu item)
return RedirectToAction("Success");
}