c# - 具有动态字段的 ASP.NET MVC 表单

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

问题

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

尝试的解决方案

现在我有一个 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/

相关文章:

c# - 使用 JsonConverter json.net 将 JSON 反序列化为对象列表

c# - 在C#中使用xPath获取节点属性值

asp.net-mvc - ASP.NET MVC : How to display strongly typed view model, 包含项目列表,其中也包含项目列表?

c# - 自定义数据验证注释 - ASP.NET MVC2 C#

c# - 使用 HierarchicalDataTemplate 展开/折叠数据绑定(bind) TreeView 项目

c# - 在 C# Windows 窗体应用程序中获取当前页面的 Html 源

c# - 将表单数据和文件发布到 ASP.NET Web API

c# - 找不到 ASP.NET View

ASP.NET MVC Beta Ajax升级问题

c# - 当请求模型实际上无效时,ModelState 有效