ASP.Net MVC - 带集合的模型,提交

Mik*_*iaz 6 c# asp.net-mvc entity-framework

我有一个看起来像的模型

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; }
}
Run Code Online (Sandbox Code Playgroud)

这是我想要做的.我想在View中填充这些内容,以及用户点击保存更改时.我想要实体框架保存.我遇到的问题是在View中我这样做

  @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>     
                                }
Run Code Online (Sandbox Code Playgroud)

我想在控制器中做这样的事情

[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);
    }
Run Code Online (Sandbox Code Playgroud)

但是,Refill不会在HttpPost上传播.它只是空的,我需要做些什么来解决它?

lan*_*nte 7

试试这个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>     
}
Run Code Online (Sandbox Code Playgroud)