开发者

if(ModelState.IsValid) doesn't work with FormsCollection. What to use instead?

T开发者_如何学Goo 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();
        }
    }

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
        {

What should one use instead of ModelState.IsValid when the action accepts a FormCollection?

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


That's normal. You need 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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜