I'm currently working on an ASP.NET MVC 4.5 application. I want to add objects to a List<T>
dynamically on a button click, using a @Html.EditorFor
and send the data to the Controller with a Form submit.
However, my problem, only the 1st element of the populated list gets sent to the controller when I submit my Form.
The area in my view where I add Elements looks like this:
<div id="addTarget" data-target="@Url.Action("AddTarget", "Offer")">
@for(var i = 0; i < Model.Targets.Count(); i++)
{
@Html.EditorFor(m => m.Targets[i])
}
</div>
My Controller looks like that:
...
public OfferVm NewOffer { get; set; } = new OfferVm();
[HttpGet]
public ActionResult Create()
{
// ...here I add my first initial target to OfferVm
NewOffer.Targets.Add(new TargetVm());
return View(NewOffer);
}
public ActionResult AddTarget()
{
// ...here I add a target to my NewOffer
NewOffer.Targets.Add(new TargetVm());
return PartialView("~/Views/Shared/EditorTemplates/TargetVm.cshtml");
}
[HttpPost]
public ActionResult Create(OfferVm offerVM)
{
//... here only 1 target is in my offerVM
}
My OfferVm class looks like this:
public class OfferVm
{
public OfferVm()
{
this.Targets = new List<TargetVm>();
}
public List<TargetVm> Targets { get; set; }
}
Do you have an idea how I can add a new target to my NewOffer.Targets List, and get the data in my controller, when I post the form?