ASP.Net MVC - model with collection, Submit

僤鯓⒐⒋嵵緔 提交于 2020-01-12 19:08:31

问题


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?


回答1:


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>     
}


来源:https://stackoverflow.com/questions/14563471/asp-net-mvc-model-with-collection-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!