回发模型为空

时间:2012-11-18 09:46:56

标签: asp.net-mvc razor postback

我更改了索引视图,以便每行包装在一个表单中:

Index.cshtml

@model IEnumerable<LevEl.Models.Page>

@foreach (var item in Model)
{
  using (Html.BeginForm("Edit", "Pages", item, FormMethod.Post, new { id = "itemForm_" + item.PageId }))
  { 
  <tr>
    <td>
      @Html.DisplayFor(modelItem => item.Title)
    </td>
    ...
    ... more fields
    ...
    <td>
      @Html.CheckBoxFor(modelItem => item.IsPublished, new { onClick = "$(itemForm_" + item.PageId + ").submit();" })
    </td>
    <td>
      @Html.ActionLink("Edit", "Edit", new { id = item.PageId }) | @Html.ActionLink("Details", "Details", new { id = item.PageId }) | @Html.ActionLink("Delete", "Delete", new { id = item.PageId })
    </td>
  </tr>
  }
}

这是我的控制器:

PagesController.cs

public ActionResult Index()
{
  return View(db.Pages.Include(p => p.Language).ToList());
}

[HttpPost]
public ActionResult Edit(Page page)
{
  var method = Request.HttpMethod;

  if (ModelState.IsValid)
  {
    if (page.PageContents.GroupBy(pc => pc.Language).Any(g => g.Count() > 1))
      return HttpNotFound("A page cannot have two translations in the same language.");

    db.Entry(page).State = EntityState.Modified;
    db.SaveChanges();
    ClearMenuKeys();
    return RedirectToAction("Index");
  }
  return View(page);
}

当我在复选框中切换值并且到达控制器时,page为空。 如何在回发时传递整个page对象?

1 个答案:

答案 0 :(得分:1)

在我看来,您的HTML不会存储Page的值。 @Html.DisplayFor仅显示您必须为该字段设置@Html.HiddenFor的数据。

编辑:

@Html.DisplayFor(modelItem => item.Title)
@Html.HiddenFor(modelItem => item.Title)