我正在尝试使用一个视图来显示能够添加新记录的当前结果。我查看了这篇文章和这篇文章,并拼凑了一些我认为应该可行但不会保存到数据库中的东西。这是我的视图模型:
public class LabIndexViewModel
{
public Lab Lab { get; set; }
public IEnumerable<Lab> Labs { get; set; }
}
在我的控制器中,我的索引中有这个:
public ActionResult Index(int patid = 0, Lab lab = null)
{
ViewBag.Finalize = PatientSubmitted(patid);
ViewBag.DispPatientId = patid;
ViewBag.CheckButtonStatus = ButtonSubmitted(patid);
var labs = db.Labs.Where(l => l.PatientId == patid && l.Active);
LabIndexViewModel model = new LabIndexViewModel();
model.Labs = labs.ToList();
model.Lab = lab;
SetViewBagLists();
return View(model);
}
然后在我的帖子中它不会保存:
[HttpPost]
public ActionResult Create(LabIndexViewModel labindex)
{
ViewBag.DispPatientId = labindex.Lab.PatientId;
Lab lab = labindex.Lab;
try
{
lab.Active = true;
db.Labs.Add(lab);
db.SaveChanges();
return RedirectToAction("Index", "Lab", new { patid = lab.PatientId });
}
catch
{
ViewBag.Phase = new SelectList(StatusList(), "Text", "Value");
ViewBag.Name = new SelectList(db.LabOptions, "Test", "Value", lab.Name);
return View(lab);
}
}
这是我在视图中提交数据的部分内容:
@model PamperWeb.Models.LabIndexViewModel
@using (Html.BeginForm("Create", "Lab")) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Lab</legend>
<tr>
<td>
@Html.DropDownList("Name", String.Empty)
@Html.ValidationMessageFor(model => model.Lab.Name)
</td>
<td>
@Html.EditorFor(model => model.Lab.Value)
@Html.ValidationMessageFor(model => model.Lab.Value)
</td>
<td>
@Html.EditorFor(model => model.Lab.Given)
@Html.ValidationMessageFor(model => model.Lab.Given)
</td>
<td>
@Html.EditorFor(model => model.Lab.TimeGiven)
@Html.ValidationMessageFor(model => model.Lab.TimeGiven)
</td>
<td>
@Html.DropDownList("Phase", String.Empty)
@Html.ValidationMessageFor(model => model.Lab.Phase)
</td>
@Html.HiddenFor(model => model.Lab.PatientId)
<td>
<input type="submit" value="Create" />
</td>
</tr>
</fieldset>
}
有人对如何进行这项工作有任何想法或有一个很好的例子吗?