2

我有这个控制器的创建方法

[HttpPost]
    public ActionResult Create(Topic topic)
    {
        if (ModelState.IsValid)
        {
            topicRepo.Add(topic);
            topicRepo.Save();

            return RedirectToAction("Details", new { id = topic.ID });
        }
        return View(topic);
    }

这用于编辑

        [HttpPost]
        public ActionResult Edit(int id, FormCollection formCollection)
        {
            Topic topic = topicRepo.getTopic(id);
            if (ModelState.IsValid)
            {
                UpdateModel<Topic>(topic);
                topicRepo.Save();
                return RedirectToAction("Details", new { id = topic.ID });
            }
            return View(topic);
        }

这两种方法都使用公共部分页面 (.ascx)。

验证在我尝试创建主题时有效,但在我尝试编辑时无效

4

1 回答 1

8

这很正常。在第一个示例中,您使用模型作为操作参数。当默认模型绑定器尝试从请求中绑定此模型时,它将自动调用验证,并且当您输入ModelState.IsValid已分配的操作时。

在第二个示例中,您的操作没有模型,只有键/值集合并且没有模型验证是没有意义的。UpdateModel<TModel>验证由在您的示例中调用调用的方法触发ModelState.IsValid

所以你可以试试这个:

[HttpPost]
public ActionResult Edit(int id)
{
    Topic topic = topicRepo.getTopic(id);
    UpdateModel<Topic>(topic);
    if (ModelState.IsValid)
    {
        topicRepo.Save();
        return RedirectToAction("Details", new { id = topic.ID });
    }
    return View(topic);
}
于 2011-01-21T15:25:56.183 回答