Reputation: 2065
I have a Model that looks like
public class Patient
{
private ICollection<Refill> _refills = new List<Refill>();
public int Id { get; set; }
public string FirstName { get; set; }
public virtual ICollection<Refill> Refills
{
get { return _refills; }
set { _refills = value; }
}
}
public class Refill
{
public int Id { get; set; }
public RefillActivityStatus RefillActivityStatus { get; set; }
public DateTime? RefillDate { get; set; }
public RefillType RefillType { get; set; }
public string RXNumber { get; set; }
}
Here is what I am trying to do. I would like to Populate these in the View and when the user clicks save changes. I would like Entity Framework to save. The problem I am having is in the View I do this
@foreach (var m in Model.Refills)
{
@Html.HiddenFor(model=>m.Id)
<div class="editor-label">
@Html.LabelFor(model => m.RXNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => m.RXNumber)
</div>
}
I am trying to do in the Controller something like this
[HttpPost]
public ActionResult Details(Patient patient)
{
Patient p = db.Patients.Find(patient.Id);
db.Entry(p).State = EntityState.Modified;
db.Entry(p).CurrentValues.SetValues(patient);
// Would include Refill changes too but it doesn't
db.SaveChanges();
return View(p);
}
However, Refills doesn't propagate on HttpPost. It is just empty, what do I need to do to fix it?
Upvotes: 6
Views: 9413
Reputation: 7336
Try this insted of your foreach
:
@for (int i = 0; i < Model.Refills.Count(); i++)
{
@Html.Hidden("Refills[" + i + "].Id", Model.Refills[i].Id)
<div class="editor-label">
@Html.Label("Refills[" + i + "].RXNumber", Model.Refills[i].RXNumber)
</div>
<div class="editor-field">
@Html.Editor("Refills[" + i + "].RXNumber")
</div>
}
Upvotes: 7