如何使用Razor创建复杂的表单,允许编辑导航属性?

时间:2017-02-08 20:42:56

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

我有一个名为Report的实体类。与之相关联的我有三个其他类的HashSet,ReportRecipients,ReportAuthors和AuthorizedUsers。三个HashSets定义了报告与收件人,作者和用户表之间的多对多关系。

在我的剃刀中,我有:

@for (int i = 0; i < Model.ReportRecipients.Count; i++)
{
    @Html.HiddenFor(model => model.ReportRecipients.ElementAt(i).ReportRecipient.ID)
    @Html.CheckBoxFor(model => model.ReportRecipients.ElementAt(i).ReportShared)
    @Html.TextBoxFor(model => model.ReportRecipients.ElementAt(i).DueDate)
    @Html.HiddenFor(model => model.ReportRecipients.ElementAt(i).ReportRecipient.Email)
    @Html.HiddenFor(model => model.ReportRecipients.ElementAt(i).ReportRecipient.Phone)
    ...
}

我的报告类如下:

[Table("Report")]
public partial class Report
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Report()
    {
        AuditLogs = new HashSet<AuditLog>();
        AuthorizedUsers = new HashSet<AuthorizedUser>();
        ReportRecipients= new HashSet<ReportRecipient>();
        ReportAuthors= new HashSet<ReportAuthor>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long ID { get; set; }

    [Key]
    [StringLength(15)]
    [DisplayName("Report Number")]
    public string ReportNumber { get; set; }

    ...

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<AuditLog> AuditLogs { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<AuthorizedUser> AuthorizedUsers{ get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<ReportAuthor> ReportAuthors{ get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<ReportRecipient> ReportRecipients{ get; set; }
}

但是,当我提交表单时,我会在我的代码中获取导航属性的空值或空值异常。

我的循环错误是什么?如果我无法使用MVC,我将不得不在AngularJS中重写整个表单。

感谢。

0 个答案:

没有答案