How to Edit and Save ViewModels data back to database

后端 未结 3 1225
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 23:40

I have a ViewModel which is joined by three Entities to get data from all entities into one view form. Although i succeeded to implement the same. But i have no idea how to Edit

3条回答
  •  猫巷女王i
    2021-02-05 23:53

    First of all, it's really good that you are using ViewModels but for this particular case, it's probably not necessary, your Create view could look like this:

    @model MvcApplication1.Models.Doctor
    
    //other fields here
    
    
    @Html.LabelFor(model => model.DoctorAddress.Address)
    @Html.EditorFor(model => model.DoctorAddress.Address) @Html.ValidationMessageFor(model => model.DoctorAddress.Address)
    @Html.LabelFor(model => model.DoctorCharge.IPDCharge)
    @Html.EditorFor(model => model.DoctorCharge.IPDCharge) @Html.ValidationMessageFor(model => model.DoctorCharge.IPDCharge)
    //other fields here

    Then your Doctor controller:

    [HttpPost]
    public ActionResult Create(Doctor doctor)
    {
        if (ModelState.IsValid)
        {
            db.Doctors.Add(doctor);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    
        return View(doctor);
    }
    
    Your `Edit` action could then look like this:
    
    [HttpGet]
    public ActionResult Edit(int id = 0)
    {
        Doctor doctor = db.Doctors.Find(id);
        if (doctor == null)
        {
            return HttpNotFound();
        }
        return View(doctor);
    }
    
    [HttpPost]
    public ActionResult Edit(Doctor doctor)
    {
        if (ModelState.IsValid)
        {
            db.Entry(doctor).State = EntityState.Modified;
            db.Entry(doctor.DoctorAddress).State = EntityState.Modified;
            db.Entry(doctor.DoctorCharge).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(doctor);
    }
    

    If you want to keep your ViewModel then it could look like this:

    [HttpPost]
    public ActionResult Edit(DoctorViewModel doctorViewModel)
    {
        if (ModelState.IsValid)
        {
            var doctorAddress = doctorViewModel.DoctorAddress;
            var doctorCharge = doctorViewModel.DoctorCharge;
            var doctor = doctorViewModel.Doctor;
            db.Entry(doctorAddress).State = EntityState.Modified;
            db.Entry(doctorCharge).State = EntityState.Modified;
            db.Entry(doctor).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(doctor);
    }
    

提交回复
热议问题