asp.net-mvc - 将对象列表绑定(bind)到表单

标签 asp.net-mvc asp.net-core model-binding

我有一个类Signature对象:

public class Signature
    {
        public int SignatureID { get; set; }
        public int FormID { get; set; }
        public string Title { get; set; }
        public string Email { get; set; }
        [Display(Name = "Signed Date:")]
        public DateTime? Date { get; set; }
    }

我有一个Form.cs具有虚拟签名列表的类

public virtual List<Signature> Signatures { get; set; }

在我的 Controller 中,我通过以下方式填充列表:

form.Signatures = repository.Signatures.Where(s => s.FormID == form.FormID).ToList();

在我的表单 View 中,我显示了关联签名的列表:

@foreach (var signature in Model.Signatures)
    {
    <div class="text-center">
        <label asp-for="@signature.Title"></label>
        <input asp-for="@signature.Title" />
        <label asp-for="@signature.Email"></label>
        <input asp-for="@signature.Email" />
        <label asp-for="@signature.Date"></label>
        <input disabled asp-for="@signature.Date">
    </div>
    }

但是,我不知道如何更新表单的 POST 方法上的关联签名。例如,如果我更改 Email签名的属性并 POST 表单,模型不会将此更改绑定(bind)到 Form目的。在这种情况下,form.Signatures为空。

如何确保 <List>Signature 发生更改与表单关联的项目是否在 POST 上更新?

最佳答案

使用 for 循环生成元素,因为它会向属性名称添加索引,模型绑定(bind)器使用该索引来绑定(bind)到帖子上的列表,该列表不适用于 foreach:

@for (int i=0; i< Model.Signatures.Count; i++)
{
<div class="text-center">
    <label asp-for="@Model.Signatures[i].Title"></label>
    <input asp-for="@Model.Signatures[i].Title" />
    <label asp-for="@Model.Signatures[i].Email"></label>
    <input asp-for="@Model.Signatures[i].Email" />
    <label asp-for="@Model.Signatures[i].Date"></label>
    <input disabled asp-for="@Model.Signatures[i].Date">
</div>
}

现在,元素将以 Signatures[0].TitleSignatures[1].Title 等名称呈现,模型绑定(bind)器可以将其绑定(bind)到模型上发布。

希望有帮助。

关于asp.net-mvc - 将对象列表绑定(bind)到表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49365019/

相关文章:

jquery - ASP.NET MVC 模型与序列化绑定(bind)

asp.net-mvc - TinyMCE 应该如何在 ASP.NET MVC 页面上工作?

c# - 将 JSON 反序列化为在局部 View 中呈现的模型(restsharp 或任何其他方法)

asp.net - .resx 文件相同的 key 但大小写不同

asp.net - 是否可以将 Azure 连接到 google 云端硬盘?

asp.net - swarm 中的 Docker 容器无法看到彼此

asp.net - 如何在 css 中本地化内容 block ?

c# - 使用 Web API 对 GET 请求进行模型绑定(bind)?

asp.net-mvc - mvc3中的十进制错误-该值对于字段无效

c# - ASP.NET MVC 绑定(bind)到字典