0

所以我的故事是我在发布到控制器时遇到问题,视图似乎工作正常。当回发发生时,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
4

2 回答 2

0

您应该在帮助程序中引用模型的属性,以便为您的控件正确生成名称:

@Html.HiddenFor(model => Model.cbItems)

应该

@Html.HiddenFor(model => model.cbItems)
于 2013-04-22T19:10:16.897 回答
0

模型绑定不会自动发生,项目需要采用某种格式才能绑定到 POST 操作中的列表属性。看看这个

尝试检查 DOM 中 BookId 属性的值,确认它是 1,否则应该正常绑定。

于 2013-04-22T19:00:22.347 回答