4

我正在开发一个 ASP.net MVC 项目,并且我正在使用CheckBoxFor辅助方法为boolean我的模型中的 a 提供值,如下所示:

@Html.CheckBoxFor(m => m.ShouldSaveSearch, new { id="ShouldSaveSearch"})

如果该复选框被用户选中,则它可以完全正常工作并且当控制器接收到模型时。ShouldSaveSearch 属性将设置为 true。

[HttpGet]
public ActionResult Search(int studentSearchId = -1)
{
    return View(new StudentSearchModel(studentSearchId));
}

[HttpPost]
public ActionResult Search(StudentSearchModel m)
{
    ViewBag.SearchResults = Hub.Web.Models.Student.StudentSearchModel.Search(m);
    Hub.Web.Models.Student.StudentSearchModel.Save(m);
    m.ShouldSaveSearch = false;
    m.ShouldShareSearch = false;
    m.SavedSearchName = "";
    m.SavedSearchDescription = "";

    return View(m);
}

然后我将ShouldSaveSearch属性设置为false,然后返回与最初提交的相同模型的相同视图。

但是,当视图呈现时,此属性的复选框仍处于选中状态。有什么我遗漏的东西阻止复选框取消选中吗?

4

3 回答 3

2

您似乎希望将复选框默认为未选中。这与lambda的真/假值无关,而是与检查属性的值相关联

@Html.CheckBoxFor(m => m.ShouldSaveSearch, new { @checked="false"})

对方的观点同样重要。清除模型状态!

于 2013-02-28T21:21:01.970 回答
1

这听起来像是这个问题这里ModelState讨论的问题

简而言之,HtmlHelper 显示ModelState值 not Model。有关更多详细信息,请参阅问题。

可能的选项:

  • 按照 42 的建议实现 post-redirect-get 模式
  • 使用集合重置复选框值ModelState,例如ModelState["ShouldSaveSearch"].Value = false
于 2013-02-28T21:20:26.917 回答
1

The problem here is that if you return the same view to which you posted with the model data, MVC will think that you are returning because of an error. This is a normal behavior. If you want to redisplay the view then you should implement PRG pattern (Post-Redirect-Get). You issue will be always there regardless of whether ModelState.IsValid is true or false. You should redirect to the HttpGet version of your view, passing the parameter, and loading the data. If you want to avoid loading, store the data in TempData or some other Session implementation.

UPDATE: You are calling the version of an action that receives model object. Once you persist data call

return RedirectToAction("Search", new {studentSearchId = your_value});
于 2013-02-28T21:25:04.623 回答