ASP.NET MVC动态字段表单

4

问题

我想展示一个表单,其中的值数量是可变的。但每个表单项都必须有一种关联的键。例如,表单生成一个名称、用户名和职业字段,我还需要生成键,因此在提交表单时,接收方法可以告诉哪些项目是什么。

尝试的解决方案

现在我有一个FieldItems列表,其中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>
1个回答

4
尝试使用隐藏的密钥字段
视图模型
public class BuildReportViewModel
{
    public IList<BuildReportFieldItemViewModel> Fields { get; set; }
}
public class BuildReportFieldItemViewModel
{
    public string Field;
    public string Key;
}

构建报告字段项视图模型的编辑器

@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>

1
可能是最好的解决方案。由于GUID与任何其他数据都没有关联,因此您可以使用它作为您的键。 - Blast_dan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接