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 and Save data back to the database. My model classes are joined by one to one relationship.
My Models are:
public class Doctor
{
public int DoctorId { get; set; }
public string Name { get; set; }
public string Speciality { get; set; }
public virtual DoctorAddress DoctorAddress { get; set; }
public virtual DoctorCharge DoctorCharge { get; set; }
public virtual DoctorAvailablity DoctorAvailablity { get; set; }
}
public class DoctorAddress
{
public string Address { get; set; }
public string City { get; set; }
public int DoctorId { get; set; }
public virtual Doctor Doctor { get; set; }
}
public class DoctorCharge
{
public decimal OPDCharge { get; set; }
public decimal IPDCharge { get; set; }
public int DoctorId { get; set; }
public virtual Doctor Doctor { get; set; }
}
My ViewModel is:
public class DoctorViewModel
{
public Doctor Doctor { get; set; }
public DoctorAddress DoctorAddress { get; set; }
public DoctorCharge DoctorCharge { get; set; }
}
My Controller is:
public ActionResult Index()
{
var model = from t1 in db.Doctors
join d in db.DoctorAddress on t1.DoctorId equals d.DoctorId into listi
join dc in db.DoctorCharges on t1.DoctorId equals dc.DoctorId into listj
from d in listi.DefaultIfEmpty()
from dc in listj.DefaultIfEmpty()
select new DoctorDetailsViewModel.DoctorViewModel { Doctor = t1, DoctorAddress = d, DoctorCharge = dc };
return View(model.ToList());
}
My View is:
@model XXX.DoctorDetailsViewModel.DoctorViewModel
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Doctor</legend>
<div class="editor-label">
Name
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Doctor.Name)
</div>
<div class="editor-label">
OPD Charge
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DoctorCharge.OPDCharge)
</div>
<div class="editor-label">
Address
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DoctorAddress.Address)
</div> <p>
<input type="submit" value="Create" />
</p>
</fieldset>}
My Controller Class is:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Doctor doctor)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(doctor);
}
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)
{
return RedirectToAction("Index");
}
return View(doctor);
}
Please help me how do i do. Thanks in advance.