ASP.NET MVC ModelState.IsValid doesnt work

感情迁移 提交于 2019-12-22 12:54:58

问题


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


来源:https://stackoverflow.com/questions/4760472/asp-net-mvc-modelstate-isvalid-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!