【发布时间】:2019-09-19 20:56:03
【问题描述】:
我有一个CategoryModel,其中包含ItemModel 的列表项以及其他一些字符串等。
我正在尝试将列表从视图传递给控制器。视图上的模型是ABCModel,其中包含CategoryModel 类型的“类别”列表。在视图中,我只想将“活动”类别发回以进行保存。
当我这样做时,将传递活动类别并从表单添加详细信息,但项目列表为空。
.cs 模型
namespace Company.Models
{
public class ABCModel
{
public IList<CategoryModel> Categories;
public SummaryModel Summary;
}
}
namespace Company.Models
{
public class CategoryModel
{
public string Label { get; set; }
public bool Active { get; set; }
public decimal Amount { get; set; }
public string Frequency { get; set; }
public string Type { get; set; }
public List<ItemModel> Items;
}
)
namespace Company.Models
{
public class ItemModel
{
public string Label { get; set; }
public string Explanation { get; set; }
public string Amount { get; set; }
public string Frequency { get; set; }
public bool Flag { get; set; }
public string Note { get; set; }
}
}
控制器
[HttpPost]
public ActionResult SaveItems([FromForm] CategoryModel activeCategoryModel, [FromForm] List<ItemModel> items, [FromQuery] string activecategory, [FromQuery] string nextcategory)
{
...
}
查看
@model ABCModel
@{ CategoryModel nextCategory = null; }
@{ CategoryModel activeCategoryModel = null; }
@if (Model.Categories.Any())
{
@for (var i = 0; i < Model.Categories.Count; i++)
{
Company.Models.CategoryModel category = Model.Categories[i];
@if (category.Active)
{
activeCategoryModel = category;
if ((i + 1 < Model.Categories.Count) && (Model.Categories[i + 1] != null))
{
nextCategory = Model.Categories[i + 1];
}
}
}
}
<form id="ABC-form" class="needs-validation" novalidate="" asp-action="SaveItems" asp-controller="Home" method="post">
@if (activeCategoryModel != null)
{
<input asp-for="@activeCategoryModel.Label" type="hidden" />
<input asp-for="@activeCategoryModel.Active" type="hidden" />
<input asp-for="@activeCategoryModel.Amount" type="hidden" />
<input asp-for="@activeCategoryModel.Frequency" type="hidden" />
<input asp-for="@activeCategoryModel.Type" type="hidden" />
@if (activeCategoryModel.Items.Any())
{
@for (var i = 0; i < activeCategoryModel.Items.Count; i++)
{
@Html.HiddenFor(x => activeCategoryModel.Items[i].Label)
@Html.HiddenFor(x => activeCategoryModel.Items[i].Explanation)
@Html.TextBoxFor(x => items[i].Amount, new { @class = "form-control" })
}
}
}
<button id="continue" type="submit" asp-action="SaveItems" asp-route-activecategory="@activeCategoryModel.Label" asp-route-nextcategory="@(nextCategory != null ? nextCategory?.Label : null)">Continue</button>
</form>
我一直在控制器上的 SaveItems 中包含 IFormCollection 作为参数,这表明项目正在以我认为可行的格式传递,但模型只显示输入的值,项目列表是空。
如何从视图中填充活动类别模型上的项目列表?
【问题讨论】:
-
你的
@Html.TextBoxFor(x => activeCategoryModel.Items[i].Amount, new { @class = "form-control" })不是@Html.TextBoxFor(x => items[i].Amount, new { @class = "form-control" })吗?
标签: c# html asp.net-mvc razor asp.net-core-2.0