如果(ModelState.IsValid)不与FormsCollection工作。改用什么? [英] if(ModelState.IsValid) doesn't work with FormsCollection. What to use instead?

查看:245
本文介绍了如果(ModelState.IsValid)不与FormsCollection工作。改用什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要验证绑定到一个具体类型HttpPost行动,我可以用ModelState.IsValid

To validate a HttpPost action that's bound to a concrete type, I can use ModelState.IsValid

    public ActionResult Create(MyModelType myModel)
    {
        if(ModelState.IsValid)
        {
            // Do some stuff
            return RedirectToAction("Details", 0);
        }
        else
        {
            return View();
        }
    }

这显然不会与工作的FormCollection ,因为没有模型验证

This obviously won't work with a FormCollection, because there is no model to validate

    public ActionResult Create(FormCollection collection)
    {
        if(ModelState.IsValid) // Never invalid
        {

什么应在使用,而不是 ModelState.IsValid 时的动作接受的FormCollection

P.S。千道歉,我知道这是一个愚蠢的问题

P.S. A thousand apologies, I know this is a dumb question

推荐答案

这是正常的。您需要的UpdateModel

public ActionResult Create()
{
    var model = new MyModelType();
    UpdateModel(model);
    if(ModelState.IsValid) 
    {
        ...
    }
    ...
}

在第一种情况下默认的模型绑定被调用,因为它需要你的模型从请求绑定。然后,这个默认模型粘结剂将根据您的数据标注规则执行验证。在第二种情况下,你什么都不做。该控制器的动作没有你的模型,并进行验证其数据注解的知识。因此模型的状态会一直有效,没有什么会使其无效。

In the first case the default model binder is invoked because it needs to bind your model from the request. This default model binder will then based on your Data Annotation rules perform the validation. In the second case you do nothing. The controller action has no knowledge of your model and its data annotations for validation. So the model state will always be valid as there is nothing that would make it invalid.

这是说,你应该总是使用第一种方法。 的FormCollection 仅仅是无用的。即使你用第二个方法去(我完全不推荐),你可以看到你不需要任何的FormCollection。

This being said, you should always use the first approach. FormCollection is just useless. Even if you go with the second approach (which I totally wouldn't recommend) as you can see you don't need any FormCollection.

这篇关于如果(ModelState.IsValid)不与FormsCollection工作。改用什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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