ASP.NET MVC ModelState.IsValid不工作
我有此控制器对create方法
I've this controller's method for create
[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)。
Both of these methods use common partial page (.ascx).
验证工作,当我尝试创建话题,但是当我尝试编辑它不能正常工作
Validation works when I try to create topic but doesn't work when I try to edit it
这是正常的。在第一个例子使用的是模型作为操作参数。当默认的模型绑定试图从它会自动调用验证和要求此模型绑定,当你进入操作的 ModelState.IsValid
已被分配。
That's normal. In the first example you are using a model as action parameter. When the default model binder tries to bind this model from the request it will automatically invoke validation and when you enter the action the ModelState.IsValid
is already assigned.
在第二个例子中你的行为概不模型中,只有一个键/值集合和不带模型验证是没有意义的。的TModel&GT; 方法,它在你的例子被调用的在的 ModelState.IsValid $验证是由
的UpdateModel&LT触发C $ C>电话。
In the second example your action takes no model, only a key/value collection and without a model validation makes no sense. Validation is triggered by the UpdateModel<TModel>
method which in your example is invoked after the ModelState.IsValid
call.
所以,你可以试试这个:
So you could try this:
[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);
}