I am currently working on an ASP.NET MVC 4.5 application. I want to add objects to List<T>dynamically by clicking a button, using @Html.EditorForand submitting data to the controller using the form.
However, my problem is that only the 1st element of the populated list is sent to the controller when submitting my form.
In my view, where I add Elements, it 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 is as follows:
...
public OfferVm NewOffer { get; set; } = new OfferVm();
[HttpGet]
public ActionResult Create()
{
NewOffer.Targets.Add(new TargetVm());
return View(NewOffer);
}
public ActionResult AddTarget()
{
NewOffer.Targets.Add(new TargetVm());
return PartialView("~/Views/Shared/EditorTemplates/TargetVm.cshtml");
}
[HttpPost]
public ActionResult Create(OfferVm offerVM)
{
}
The My OfferVm class is as follows:
public class OfferVm
{
public OfferVm()
{
this.Targets = new List<TargetVm>();
}
public List<TargetVm> Targets { get; set; }
}
Do you have an idea how to add a new target to your NewOffer.Targets list and get the data in my controller when I submit the form?