0

I start using ASP.NET MVC4 and I've some little troubles:) I have a viewModel that looks like this:

 public class Adulte{
     public string Name {get;set;}
     public List<Child> Children {get;set;}
 }
 public class Child{
     public string Name {get;set;}
     public int Age {get;set;}
 }

I would like to dynamically add/remove child item from my view.

   @Ajax.ActionLink("Add Child", 
       "AddChild", 
       new { ???= ??? }, 
       new AjaxOptions
      {
         InsertionMode = InsertionMode.InsertAfter,
         HttpMethod = "POST"
      }
    )
    .....
    @using (Html.BeginForm())
    {
         <div id="parent">
           <p>
            @Html.Label("Name")
            @Html.TextBoxFor(x => x.Name)
          <p>
          </div>
          <div id="children">
          </div>
          <input type="submit" value="Save" />
    }

But I don't know which parameter to send to the ActionLink, I test with Model as well as Model.Children without success.

This can be done?

Any help?

Stan92
  • 453
  • 1
  • 8
  • 21
  • What model are you passing to your view? – Longball27 Jun 26 '13 at 06:31
  • I tried to pass Adulte and from the controller. [AcceptVerbs(HttpVerbs.Post)] public ActionResult AddChild(Adulte AdulteItem) { if (AdulteItem.Children == null) AdulteItem.Children = new List(); AdulteItem.Children.Add(new Child()); return PartialView("ChildView", AdulteItem); } – Stan92 Jun 26 '13 at 06:50

1 Answers1

1

Have some key property in Adulte or Child. Or else, if Name property is going to be unique, you can send Name for Adulte or Child.

public class Adulte{
   public int AdulteId {get;set;}
   public string Name {get;set;}
   public List<Child> Children {get;set;}
}
public class Child{
   public int ChildId {get;set;}
   public int Age {get;set;}
}

In View, (to delete Child)

@Ajax.ActionLink("Remove Child", 
   "RemoveChild", 
   new { ChildId = ChildId }, 
   new AjaxOptions
  {
     InsertionMode = InsertionMode.InsertAfter,
     HttpMethod = "POST"
  }
)

And to add Child, you can pass it without parameter.

...
"AddChild", 
   null, 
   new AjaxOptions....
Paritosh
  • 11,144
  • 5
  • 56
  • 74
  • Thanks..could u please tell me how to configure the partialView for the AddChild? I tried what u said, but when I validate the whole final form my Adulte.Children (after my
    forgot to mention my ) is always empty. Sorry for this newbie problem.. Just need to get the picture.
    – Stan92 Jun 26 '13 at 07:24
  • [Using partial views in ASP.net MVC 4](http://stackoverflow.com/questions/13934671/using-partial-views-in-asp-net-mvc-4), [using Ajax for partial view loading in .NET MVC4](http://stackoverflow.com/questions/14529936/using-ajax-for-partial-view-loading-in-net-mvc4) - help youself – Paritosh Jun 26 '13 at 07:29