简体   繁体   中英

ASP.NET MVC ModelState.IsValid doesnt work

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM