2015-04-01 58 views
0

我似乎無法找到如何爲一對多複選框構建適當的解決方案。C#實體概覽一對多複選框表

所以我有什麼:

我有一篇文章和管理員用戶可以設置用戶權限那篇文章。 因此,在我的文章右側頁面中,您可以查看所有用戶的情況。

我的文章:

public partial class Artikel 
    { 
     public Artikel() 
     { 
      this.ArtikelLinks = new HashSet<ArtikelLink>(); 
      this.ArtikelRights = new HashSet<ArtikelRight>(); 
     } 

     public int id { get; set; } 
     public string code { get; set; } 
     public string naam { get; set; } 

     public virtual ICollection<ArtikelLink> ArtikelLinks { get; set; } 
     public virtual ICollection<ArtikelRight> ArtikelRights { get; set; } 
    } 

我的權益類

public partial class ArtikelRight 
    { 
     public int id { get; set; } 
     public System.Guid userId { get; set; } 
     public int artikelId { get; set; } 
     public bool hasRight { get; set; } 

     public virtual Artikel Artikel { get; set; } 
    } 

如何構建我的看法?我嘗試了幾種方法,但我似乎無法保存我的數據。 這是我的權利,此刻查看:

@using (Html.BeginForm()) { 
     <table width="90%" align="center" class="table table-striped"> 
      <thead> 
       <tr> 
        <th align="left">Gebruiker</th> 
        <th align="left">Heeft toegang</th> 
       </tr> 
      </thead> 
       @Html.EditorFor(x => Model.ArtikelRights, "ArtikelRight") 
     </table> 

     <br /> 
     <div class="pull-right"> 
      <input type="submit" value="Opslaan" class="btn btn-sm beige" /> 
     </div> 
} 

這是我的部分ARTIKEL右視圖:

@model IEnumerable<GtiProducts.Models.ArtikelRight> 


@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Membership.GetUser(item.userId).UserName 
     </td> 
     <td> 
      @Html.EditorFor(x => item.hasRight) 

     </td> 
    </tr> 
} 

我的拯救行動是:

public ActionResult Rights(Artikel art) 
{ 

    repo.SaveChanges(); 
    return View(art); 
} 

當調試我的藝術.ArtikelRights爲null。 我該如何解決這個問題,以及與實體框架做到這一點的最佳解決方案是什麼?

回答

0

重命名局部使它成爲EditorTemplate - /Views/Shared/EditorTemplates/ArtikelRight.cshtml,然後進行以下修改

@model GtiProducts.Models.ArtikelRight // not IEnumerable 
<tr> 
    <td> 
    @Html.CheckBoxFor(m => m.hasRight)</td> 
    @Html.LabelFor(m => m.hasRight, "....") // the users name? 
    @Html.HiddenFor(m > m.id) // or what ever property you need to identify the ArtikelRight.cshtml 
    </td> 
</tr> 

然後在主視圖

<tbody> 
    @Html.EditorFor(x => Model.ArtikelRights) 
</tbody> 

這將正確命名你可以用在索引控制這樣他們就可以例如

<input type="checkbox" name="ArtikelRights[0].hasRight" ...> 
<input type="checkbox" name="ArtikelRights[1].hasRight" ...> 

備註:您不應在視圖中使用@Membership.GetUser(item.userId).UserName。相反,只需在視圖中創建一個只需要那些屬性的視圖模型(它看起來是idhasright,並且包括用戶顯示名稱的屬性(並將其填充到控制器中)