MVC4。我在视图上有一个动态列表,添加一个新的文本框,点击按钮(添加了一个partialView),这样用户就可以输入一个东西列表。它包含在带有提交按钮的表单元素中。
在控制器中,我尝试了三种不同的类型:
[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
我看到的所有示例都使用for列表为每个项添加索引,但它们没有使用动态列表(它具有固定长度)。
Controller接收类型应该是什么?
编辑以添加更多细节:
按钮单击会附加部分视图:
$("#add-item").on("click", function () {
$.ajax({
url: '/Accessory/AddItem',
cache: false,
success: function (html) {
$("#form-body").append(html);
}
})
return false;
})
部分视图:
@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>
主视图 - 部分附加到#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>
}
答案 0 :(得分:0)
最有可能的是,您有绑定问题。假设您发布的所有内容都是AccessoryVM
的集合,则参数应为List<AccessoryVM> form
。但是,为了使模型绑定器正确绑定发布的值,您的输入名称必须采用特定格式,即form[N].Foo
或[N].Foo
。
您还没有详细了解视图中的内容,但由于这些是动态添加的,因此您必须使用JavaScript向页面添加其他输入。如果您通过AJAX(返回部分视图)执行此操作,则需要将索引传递到端点,以便可以使用它来生成正确的输入名称。如果您正在使用Knockout,Angular等内容,则应确保使用任何模板生成输入都需要考虑索引。