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?

2
  • What model are you passing to your view? Commented Jun 26, 2013 at 6: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<Child>(); AdulteItem.Children.Add(new Child()); return PartialView("ChildView", AdulteItem); } Commented Jun 26, 2013 at 6:50

1 Answer 1

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....
Sign up to request clarification or add additional context in comments.

2 Comments

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 <div id="chilren"></div> forgot to mention my <input type="submit" value="Save" />) is always empty. Sorry for this newbie problem.. Just need to get the picture.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.