表我有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表。 我不想將新派對添加到派對桌上!
希望你明白了我的觀點。 已被困在這一兩天了,任何幫助高度讚賞,謝謝!
編輯: 如果有這方面的任何更好的解決方案,請吐了出來:)
查看'SimpleMembership Tables'查看'Membership和Roles,然後查看UsersInRoles'。嘗試和'種子'的數據,如果你有'遷移啓用' – Komengem 2013-03-17 21:43:40