所以我的故事是我在向控制器发帖时遇到问题,视图似乎运行正常。当回发发生时,tm.BookId为0(应为1)并且列表计数为0.首先我将显示模型:
public class TransferModel
{
public TransferModel()
{
cbItems = new List<CheckBoxItem>();
}
public List<CheckBoxItem> cbItems {get;set;}
public int BookId;
public class CheckBoxItem
{
public int AttributeId { get; set; }
public string Attribute { get; set; }
public bool Selected { get; set; }
}
}
控制器部分:
public ActionResult AddAttributes(int id = 0)
{
db.transMod.BookId = id;
BookInfo book = db.BookInfoes.Find(id);
var latts = db.BookAtts.ToList();
foreach (BookAtt ba in latts)
{
db.transMod.cbItems.Add(new TransferModel.CheckBoxItem { Attribute = ba.Attribute, AttributeId = ba.BookAttId, Selected = false });
}
List<BookAtt> atInList = book.BookAtts.ToList();
foreach (TransferModel.CheckBoxItem cb in db.transMod.cbItems)
{
if (atInList.Exists(item => item.Attribute == cb.Attribute))
cb.Selected = true;
}
return View(db.transMod);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddAttributes(TransferModel tm)
{
List<BookAtt> atPool = db.BookAtts.ToList();
BookInfo book = db.BookInfoes.Find(tm.BookId);
foreach (TransferModel.CheckBoxItem sel in tm.cbItems)
{
if (sel.Selected)
book.BookAtts.Add(atPool.Find(item1 => item1.Attribute == sel.Attribute));
}
db.SaveChanges();
return RedirectToAction("AddAttributes");
}`enter code here`
最后是观点:
@model BrightStar.Models.TransferModel
@{
ViewBag.Title = "Update Attributes";
}
<h2>Add Attributes</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<table>
@Html.HiddenFor(model => Model.BookId)
@Html.HiddenFor(model => Model.cbItems)
@foreach (var itm in Model.cbItems)
{
<tr>
<td>@Html.HiddenFor(mo => itm.AttributeId)</td>
<td>@Html.CheckBoxFor(mo => itm.Selected)</td>
<td>@Html.DisplayFor(mo => itm.Attribute)</td>
</tr>
}
</table>
<p>
<input type="submit" value="Save" />
</p>
}
enter code here