MVC将View模型映射到域模型

时间:2014-12-04 02:26:00

标签: c# asp.net-mvc

我正在努力弄清楚如何将我的viewModels映射到域模型,以便控制器中的索引,编辑,详细信息和删除操作结果。

我想出了如何在斯蒂芬的帮助下完成创建行动结果,但对于其他四个观点,我一无所知。我研究过,无法想出任何对我有帮助的东西。简而言之,我正在构建一个最终能够添加/删除行(子)的Web表单(父级)。我硬编码了孩子,但最终我会有一些类型的js函数来做到这一点。

我昨天了解到,每个视图使用一个viewModels可能是个好主意。在这种情况下,它将是五个viewModels。为了这个项目,我们假设我将使用映射中的所有属性。

域模型:

public class Parent
{

    public int ParentID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Child> Childs { get; set; }

}

public class Child
{
    public int ChildID { get; set; }
    public int ParentID { get; set; }

    public string Name { get; set; }
    public string DOB { get; set; }
    public string Address { get; set; }

    public virtual Parent Parent { get; set; }
}

查看模特:

public class ParentsEditVM
{

    public ParentsEditVM()
    {

    }


    public int ParentID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public IList<ChildVM> Children { get; set; }

}


public ParentsCreateVM()
    {
        Children = new List<ChildVM>()
            {
                new ChildVM(){Name="1", DOB="1", Address="1"},
                new ChildVM(){Name="2", DOB="2", Address="0"},
                new ChildVM(){Name="3", DOB="3", Address="3"},                    
            };

    }


    public int ParentID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public IList<ChildVM> Children { get; set; }

}

 public class ChildVM
{
    public int ChildID { get; set; }
    public int ParentID { get; set; }

    public string Name { get; set; }
    public string DOB { get; set; }
    public string Address { get; set; }
}

控制器:

 public class ParentsController : Controller
{
    private OnlineFormsContext db = new OnlineFormsContext();

    // GET: Parents
    public ActionResult Index()
    {
        return View(db.Parents.ToList());
    }

    // GET: Parents/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Parent parent = db.Parents.Find(id);
        if (parent == null)
        {
            return HttpNotFound();
        }
        return View(parent);
    }

    // GET: Parents/Create
    public ActionResult Create()
    {

        return View(new ParentsCreateVM());

    }

    // POST: Parents/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(ParentsCreateVM viewModel)
    {
        if (ModelState.IsValid)
        {

            var parent = new Parent()
            {
                FirstName = viewModel.FirstName,
                LastName = viewModel.LastName
            };

            db.Parents.Add(parent);

            foreach (ChildVM item in viewModel.Children)
            {

                var child = new Child()
                {
                    Name = item.Name,
                    DOB = item.DOB,
                    Address = item.Address
                };
                db.Childs.Add(child);
            }

            //Parent parent = new Parent();              
            //var employee = AutoMapper.Mapper.Map<Parent, ParentVM>(parent);                        

            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(viewModel);
    }

    // GET: Parents/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Parent parent = db.Parents.Find(id);
        if (parent == null)
        {
            return HttpNotFound();
        }


        // http://forums.asp.net/t/1900785.aspx?Editing+one+to+many+relationships+MVC+4+EF
        //var model = new ParentsEditVM(parent);
        //return View(model);
        return View(new ParentsEditVM());
        //return View(parent);
    }

    // POST: Parents/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ParentID,FirstName,LastName")] Parent parent)
    {
        if (ModelState.IsValid)
        {
            db.Entry(parent).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(parent);
    }

    // GET: Parents/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Parent parent = db.Parents.Find(id);
        if (parent == null)
        {
            return HttpNotFound();
        }
        return View(parent);
    }

    // POST: Parents/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Parent parent = db.Parents.Find(id);
        db.Parents.Remove(parent);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

1 个答案:

答案 0 :(得分:0)

将域模型映射到编辑方法

中的视图模型
Parent p = db.Parents.Find(id);

ParentsEditVM model = new ParentsEditVM()
{
  ParentID = p.ParentID,
  FirstName =p.FirstName,
  LastName = p.LastName,
  Children = p.Childs.Select(c => new ChildVM()
  {
    ChildID = c.ChildID,
    Name = c.Name,
    ... etc
  }).ToList(),
};
....
return View(model);

请注意。我不认为ChildVM确实需要包含属性ParentID(当您回帖时,您已经知道来自ParentID的{​​{1}}。此外,您可能会因此过度复杂化使用单独的创建和编辑视图模型,如果唯一的区别在于,在创建中,ParentsEditVM将为空并且在ParentID中,它将具有值。并且是否必须具有{{1通常,您可能在EditGET视图上有一个删除按钮/链接(根据用户权限可能显示也可能不显示),可能是{{1}只需将Index的{​​{1}}发回Details方法的元素