I am trying to use one view in which I display current results which has the ability to add a new record. I looked at this post and also this post and pieced together something I think should work but it will not save to the database. Here is my view model:
public class LabIndexViewModel
{
public Lab Lab { get; set; }
public IEnumerable<Lab> Labs { get; set; }
}
And in my controller I have this in my index:
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);
}
Then in my post where it will not save:
[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);
}
}
Here is my partial where I submit the data in my view:
@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>
}
Anybody have any idea on how to make this work or have a good example?