我想使用一個視圖,其中我顯示當前的結果,有能力添加一條新的記錄。我看了一下this的帖子,還有this的帖子,把我認爲應該可以工作的東西拼湊在一起,但它不會保存到數據庫中。這裏是我的視圖模型:使用一個視圖的索引和創建在mvc4
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>
}
任何人對如何做這項工作有什麼想法或有一個很好的例子?
當你說它沒有保存時,你是什麼意思?你有沒有放置一個斷點來測試它是否進入'Create'動作? –
@AndreCalil是的。它擊中控制器後,但一旦它擊中db.save(實驗室)它炸彈並擊中catch並重定向到創建get方法。 – Xaxum
不錯!那麼例外是什麼......? –