2016-03-25 4 views
0

Проблема очень простая :)mvc5 icollection всегда null

У меня есть две модели Родитель и ребенок. Родительская модель содержит коллекцию детей. Дело в том, что я могу видеть детей в поле зрения, но я не могу сохранить изменения к ним. Я потратил много часов на привязку к решению этой проблемы. Любая помощь будет оценена воодушевлением.

родительская модель

namespace WebApplication1.Models 
{ 
    public class Parent 
    { 
     //public Parent() 
     //{ 
     // Child = new Collection<Child>(); 
     //} 

     public int ParentId { get; set; } 
     public string ZmiennaParent1 { get; set; } 

     public ICollection<Child> Child { get; set; } 
    } 
} 

Ребенок модель:

namespace WebApplication1.Models 
{ 
    public class Child 
    { 
     public int ChildId { get; set; } 
     public string ZmiennaChild1 { get; set; } 

     public int ParentId { get; set; } 
     public virtual Parent Parent { get; set; } 
    } 
} 

мой взгляд:

@for (int i = 0; i < Model.Child.Count(); i++) 
{ 
    @Html.EditorFor(model => Model.Child.ElementAt(i).ZmiennaChild1, new { htmlAttributes = new { @class = "form-control" } }) 
} 

и мой контроллер:

// GET:/Родитель/Редактировать/5 public ActionResult Edit (int? id) { if (id == null) { return new HttpStatusCodeResult (HttpStatusCode.BadRequest); }

var parent = db.Parents.Include(u => u.Child).SingleOrDefault(u => u.ParentId == id); 

    if (parent == null) 
    { 
     return HttpNotFound(); 
    } 
    return View(parent); 
} 

// POST: /Parent/Edit/5 
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
[HttpPost] 
[ValidateAntiForgeryToken] 
//public ActionResult Edit(Parent parent) 
public ActionResult Edit([Bind(Include="ParentId,ZmiennaParent1, Children")] Parent parent) 
{ 
    if (ModelState.IsValid) 
    { 
     if (parent.Child != null) 
     { 
      foreach (Child element in parent.Child) 
      { 
       db.Entry(element).State = EntityState.Modified; 
      } 
      db.SaveChanges(); 
     } 

     db.Entry(parent).State = EntityState.Modified; 
     db.SaveChanges(); 

     return RedirectToAction("Index"); 
    } 
    return View(parent); 
} 

Я буду очень признателен за любую помощь:/Как я писал дело в том, что я в состоянии отобразить связанные ребенок, но не в состоянии их изменить.

+1

Почему вы отметили это asp-classic, я не вижу здесь никакого классического asp. –

ответ

0

Нет Дети Недвижимость на Родительской, есть детская. Но атрибут Binding говорит «Дети». Измените атрибут на ...

public ActionResult Edit([Bind(Include="ParentId,ZmiennaParent1, Child")] Parent parent) 
+0

ЭТО ЭТО !!! СПАСИБО БОЛЬШОЕ !!! Я потратил 5,5 часа за попытку решить это !!! : D: D: D – Blue

+0

извините, я не могу голосовать в этот момент, я думаю, что мой голос doest'y count ... :( – Blue

Смежные вопросы