我有 3 张桌子:
轮询:
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; }
PartyInPoll(两个主键)
* 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 循环却没有。它不会与所选缔约方的视图列表框进行通信,并且循环将 7(?!)个新行添加到 Party 表和 PartyInPoll 表。所以我想要的当然是让从视图中的 ListBox 中选择的值通过 foreach 循环发送,以便更新 PartyInPoll 表。我不希望将新的派对添加到派对表中!!
希望你明白我的意思。卡在这几天了,非常感谢任何帮助,谢谢!
编辑:如果有任何更好的解决方案,请吐出来:)