ASP.NET MVC ModelState.IsValid doesnt work

2019-05-24 04:12发布

问题:

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);
    }

and this for edit

        [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);
        }

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

回答1:

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.

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);
}