2013-03-17 109 views
0

表我有3個表:ASP.NET MVC實體框架插入許多一對多使用MultiSelectList

投票:

public int PollId { get; set; } 
public string PollTitle { get; set; } 

public virtual ICollection<Party> Parties { get; set; } 

public int PartyId { get; set; } 
public string PartyName { get; set; } 

public virtual ICollection<Poll> Polls { get; set; } 

PartiesInPoll(兩個主鍵)

* int PartyId 
* int PollId 

在我PollController:

private VoterEntities db = new VoterEntities(); 

// 
     // GET: /Polls/Create 

     public ActionResult Create() 
     { 
      ViewBag.PartyId = new MultiSelectList(db.Parties, "PartyId", "PartyName"); 
      return View(); 
     } 

     // 
     // POST: /Polls/Create 

     [HttpPost] 
     public ActionResult Create(Poll poll) 
     { 

      //var parti = db.Parties.Find(partyId); 
      if (ModelState.IsValid) 
      { 
       var pList = new List<Party>(); 
       foreach (var pId in "PartyId") 
       { 
        pList.Add(new Party 
        { 
         PartyId = pId 
        }); 
       } 
       poll.Parties = pList; 
       db.Polls.Add(poll); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 
      ViewBag.PartyId = new MultiSelectList(db.Parties, "PartyId", "PartyName", poll.Parties); 
      return View(poll); 
     } 

我的觀點:

@model VoterMVC.Models.Poll 

@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary(true) 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.PollTitle) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.PollTitle) 
      @Html.ValidationMessageFor(model => model.PollTitle) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Parties) 
     </div> 
     <div class="editor-field"> 
      @Html.ListBox("PartyId") 
      @Html.ValidationMessageFor(model => model.Parties) 
     </div> 

     <p> 
      <input type="submit" value="Create" /> 
     </p> 
} 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 

現在大部分的工作就像一個魅力,但foreach循環沒有。它不會與所選派對的視圖ListBox進行通信,並且該循環將7(?!)個新行添加到Party表和PartiesInPoll表中。 所以我想要的是讓從列表框中選擇的值從視圖中發送,通過foreach循環發送,以便更新PartiesInPoll表。 我不想將新派對添加到派對桌上!

希望你明白了我的觀點。 已被困在這一兩天了,任何幫助高度讚賞,謝謝!

編輯: 如果有這方面的任何更好的解決方案,請吐了出來:)

+0

查看'SimpleMembership Tables'查看'Membership和Roles,然後查看UsersInRoles'。嘗試和'種子'的數據,如果你有'遷移啓用' – Komengem 2013-03-17 21:43:40

回答

0

此代碼看起來錯誤:

foreach (var pId "PartyId") 

它不應該編譯。可能你有

foreach (var pId in "PartyId") 

而這段代碼遍歷「PartyId」字符串中的字符。恰好有7個。

+0

是的,我的錯誤,當我粘貼..!在我的原始代碼中是正確的。對於那個很抱歉。 – Lars 2013-03-17 20:21:06

0

從列表框中選擇一個PartyId後,該視圖僅將該ID發送到post方法。 for循環在這種情況下變得毫無用處。你的大部分問題都來自你在數據庫中的多對多關係。閱讀更多關於here。如果你想在一個民意調查中有多個參與方創建1個*(或*到1)的關係,你會發現這樣做更容易。