问题
我想显示一个具有可变数量值的表单。然而,每个表单项都必须有一种与之关联的键。例如,表单生成名称、用户名和职业字段,我还需要生成键,以便在提交表单时,接收方方法可以分辨哪些项目是什么。
尝试的解决方案
现在我有一个 FieldItem 列表,其中 FieldItem 只是一个类,其中包含一个字符串类变量。该解决方案在填充表单时有效,但是在提交时会返回一个列表,我无法分辨哪个值属于哪个键。我正在考虑使用字典,但我不知道如何在 Razor 中实现这一点。
查看模型
public class BuildReportViewModel
{
public IList<BuildReportFieldItemViewModel> Fields { get; set; }
}
public class BuildReportFieldItemViewModel
{
public string Field { get; set; }
}
BuildReportFieldItemViewModel 的编辑器
@model BuildReportFieldItemViewModel
<div class="editor-label">
<label for="@Model.Field">@Model.Field</label>
</div>
<div class="editor-field">
<input type="text" name="@Model.Field">
</div>
最佳答案
尝试使用隐藏键域
查看模型
public class BuildReportViewModel
{
public IList<BuildReportFieldItemViewModel> Fields { get; set; }
}
public class BuildReportFieldItemViewModel
{
public string Field;
public string Key;
}
BuildReportFieldItemViewModel 的编辑器
@model BuildReportFieldItemViewModel
<div class="editor-label">
<label for="@Model.Field">@Model.Field</label>
</div>
<div class="editor-field">
@Html.TextBoxFor(x => x.Field)
@Html.Hidden(Model.Key, "key_value");
</div>
关于c# - 具有动态字段的 ASP.NET MVC 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10934993/