ASP.NET MVC ModelState.IsValid不工作 [英] ASP.NET MVC ModelState.IsValid doesnt work

查看:130
本文介绍了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);
}

这篇关于ASP.NET MVC ModelState.IsValid不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆