【问题标题】:ASP.NET MVC Form with Dynamic Fields带有动态字段的 ASP.NET MVC 表单
【发布时间】:2012-06-08 03:17:00
【问题描述】:

问题

我想显示一个具有可变数量值的表单。但是,每个表单项都必须有一种与之关联的键。例如,表单生成姓名、用户名和职业字段,我还需要生成密钥,以便在提交表单时,接收者方法可以告诉哪些项目是什么。

尝试的解决方案

现在我有一个 FieldItems 列表,其中 FieldItem 只是一个类,其中一个类变量为 String。该解决方案在填充表单时有效,但是在提交时会返回一个列表,我无法判断哪个值属于哪个键。我正在考虑使用字典,但我不知道如何在 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>

【问题讨论】:

    标签: c# asp.net asp.net-mvc razor


    【解决方案1】:

    尝试使用隐藏的关键字段

    查看模型

    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>
    

    【讨论】:

    • 可能是最好的解决方案。您可以为密钥使用 GUID,因为它不与任何其他数据相关联。
    猜你喜欢
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多