MVC试图将模型从剃刀视图传递给控制器

时间:2013-04-22 18:46:57

标签: asp.net-mvc

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

3 个答案:

答案 0 :(得分:0)

模型绑定不会自动发生,项目需要采用特定格式才能绑定到POST操作中的列表属性。检查this

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

答案 1 :(得分:0)

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

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

应该是

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

答案 2 :(得分:0)

我找到了这个链接,解释了如何在视图中绑定复杂列表。 link