更新多个实体并返回ViewModel?

时间:2015-12-03 16:08:00

标签: c# asp.net-mvc asp.net-mvc-4

我对如何在使用ViewModel时更新两个实体感到困惑。我已经做了一些搜索,但我没有提出任何似乎可以帮助我理解这一点。

我有两个实体Person和Address。我使用ViewModel将两者结合在一起,以便在Edit.cshtml中显示它们。在我的视图顶部,我声明要使用的ViewModel。

现在,我进入实际的编辑部分。我假设我必须对每个实体进行更新,然后创建一个新的ViewModel以返回View,因为Veiw期待一个ViewModel?

我也很好奇是否有办法让View知道更新成功,所以我可以在View顶部显示一条消息,或者最好只重定向到Index View。

这是一种正确的编码方式,还是有更简化的方法来完成同样的事情?

我的.cshtml页面顶部

@model Project.Models.MemberViewModel

控制器

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult MyAccount(MemberViewModel model)
    {
        if (model.PersonId == 0)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        MemberViewModel updatedVM = new MemberViewModel();
        using (var db = new DataContext())
        {
            Person currentPerson = db.Person.Find(model.PersonId);
            if (currentPerson == null)
            {
                return HttpNotFound();
            }
            db.Entry(currentPerson).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();


            Address currentAddress = db.Address.Find(model.PersonId);
            if (currentAddress == null)
            {
                return HttpNotFound();
            }
            db.Entry(currentAddress).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();

            ////update and return a ViewModel
            //updatedVM.FirstName = currentPerson.FirstName;
            //updatedVM.LastName = currentPerson.LastName;
            //updatedVM.Address = currentAddress.Address1;
            //updatedVM.City = currentAddress.City;
            //updatedVM.State = currentAddress.State;
            //updatedVM.Zip = currentAddress.Zip;
        }

        return View(updatedVM);
    }

1 个答案:

答案 0 :(得分:1)

在我看来,最佳做法是在成功保存数据后重定向到Index.cshtml(我认为这是保持MVC清洁的全部想法):

return RedirectToAction("Index");

如果数据出现问题,我只会显示错误消息。这可以这样做: 您可以将这些添加到ViewModel:

bool hasErrors;
string errorMessage;

在视图中,您将在页面顶部实现:

@if(Model.hasErrors)
{
<div>Model.errorMessage</div>
}

这个想法是验证ViewModel构造函数内部或控制器内部的数据,如果有错误,只需设置hasErrors = true和自定义errorMessage并在view.cshtml中显示它。

希望它有所帮助。