GET&使用具有1个列表属性的ViewModel进行POST

时间:2016-08-28 19:10:47

标签: c# asp.net-mvc

好的,我希望用户能够编辑和添加更多医疗信息卡。我能够只为1个医疗信息对象做这件事但是能够处理医疗信息对象列表似乎比我想象的更难。我确信有一个解决方案,而不采取hacky bugy技巧。到目前为止我的尝试都没有奏效。我最新尝试的一个例子如下。

我尝试保存更改时出现的当前错误:

  

传递到字典中的模型项的类型为“B4B.Models.Profile”,但此字典需要“B4B.Models.WizardViewModel”类型的模型项。

模型

public class WizardViewModel
{
    public Profile _profile { get; set; }                       
    public MedicalInfo _medicalInfo { get; set; }               // Each profile can have many medical infos
    public List<MedicalInfo> medInfoList { get; set; }          // So here I decided to make it a list of medicalinfos
}

控制器

    // GET: Profiles/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        WizardViewModel wizardViewModel = new WizardViewModel();
        Profile profile = db.Profiles.Find(id);
        wizardViewModel._profile = profile;
        wizardViewModel.medInfoList = profile.MedicalInfos.ToList();          


        if (profile == null)
        {
            return HttpNotFound();
        }
        if (CurrentUser.Profiles.Contains(wizardViewModel._profile))
        {
            return View(wizardViewModel);
        }


        return RedirectToAction("Login", "Account");
     }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "_profile, medInfoList")] WizardViewModel wizardViewModel, HttpPostedFileBase upload)
    {
        if (ModelState.IsValid)
        {
           ....
            wizardViewModel._profile.Admin = CurrentUser; // comes back null so i manually reset
            db.Entry(wizardViewModel._profile).State = EntityState.Modified;            //Adds profile object into database


            foreach(var mi in wizardViewModel.medInfoList)
            {
                var medicalInfoDB = db.MedicalInfoes.Find(mi.MedicalInfoID);

                mi.ProfileID = wizardViewModel._profile.ProfileID;
              db.Entry(medicalInfoDB).CurrentValues.SetValues(wizardViewModel._medicalInfo);
                db.Entry(medicalInfoDB).State = EntityState.Modified;
            }

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

0 个答案:

没有答案