gpt4 book ai didi

asp.net-mvc - 如何编辑 ViewModels 数据并将其保存回数据库

转载 作者:行者123 更新时间:2023-12-02 11:09:39 25 4
gpt4 key购买 nike

我有一个 ViewModel,它由三个实体连接起来,以将所有实体的数据获取到一个 View 表单中。虽然我成功地实现了同样的目标。但我不知道如何编辑数据并将数据保存回数据库。我的模型类通过一对一的关系连接起来。

我的模型是:

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; }
}

我的 View 模型是:

public class DoctorViewModel
{
public Doctor Doctor { get; set; }
public DoctorAddress DoctorAddress { get; set; }
public DoctorCharge DoctorCharge { get; set; }

}

我的 Controller 是:

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());

}

我的观点是:

@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>}

我的 Controller 类是:

public ActionResult Create()
{
return View();
}

//
// POST: /Doctor/Create

[HttpPost]
public ActionResult Create(Doctor doctor)
{
if (ModelState.IsValid)
{
db.Doctors.Add(doctor);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(doctor);
}

请帮我看看我该怎么办。提前致谢。

最佳答案

在这里,用于创建:

[HttpPost]
public ActionResult Create(DoctorViewModel model)
{
if (ModelState.IsValid)
{
model.Doctor.DoctorAddress = model.DoctorAddress;
model.Doctor.DoctorCharge = model.DoctorCharge;
db.Doctors.Add(doctor);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(doctor);
}

关于asp.net-mvc - 如何编辑 ViewModels 数据并将其保存回数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18237945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com