MVC4. I have a dynamic list on a view, a new textbox is added with button click (which adds a partialView) so user can enter a list of stuff. That is contained in a form element with a submit button.
In the controller I have tried three different types:
[HttpPost]
public ActionResult Index(IEnumerable<AccessoryVM> form)
{
-- form is NULL
[HttpPost]
public ActionResult Index(AccessoryVM form)
{
-- form has only the first item in the list
[HttpPost]
public ActionResult Index(FormCollection form)
{
-- seems to receive the list, but having trouble getting the values
All the examples I have seen are using a for list to add an index to each item, but they aren't using a dynamic list (it has a fixed length).
What should the Controller receiving type be?
EDIT to add more detail:
Button click appends partial view:
$("#add-item").on("click", function () {
$.ajax({
url: '/Accessory/AddItem',
cache: false,
success: function (html) {
$("#form-body").append(html);
}
})
return false;
})
Partial View:
@model EmployeeHardwareRequest.Models.ViewModels.AccessoryVM
<div class="form-group col-md-3">
@Html.LabelFor(model => model.ItemDescription, htmlAttributes: new { @class = "control-label" })
<div>
@Html.DropDownListFor(model => model.AccessoryId, Model.AccessoryDdl, new { @class = "form-control" })
</div>
</div>
<div class="form-group col-md-9">
@Html.LabelFor(model => model.ProductLink, htmlAttributes: new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.ProductLink, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ProductLink, "", new { @class = "text-danger" })
</div>
</div>
Main View - partial is appended to the #form-body:
@using (Html.BeginForm("Index", "Accessory", FormMethod.Post, new { @id="accessory-form", @class = "form-horizontal" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div id="form-body">
<div class="form-group col-md-3">
@Html.LabelFor(model => model.ItemDescription, htmlAttributes: new { @class = "control-label" })
<div>
@Html.DropDownListFor(model => model.SelectedAccessory, Model.AccessoryDdl, new { @class = "form-control" })
</div>
</div>
<div class="form-group col-md-9">
@Html.LabelFor(model => model.ProductLink, htmlAttributes: new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.ProductLink, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ProductLink, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button id="add-item" class="btn btn-primary">Add Another Item</button>
</div>
<div class="col-md-6">
<input type="submit" value="Select Software" class="btn btn-default pull-right" />
</div>
</div>
}