测试的ModelState总是在asp.net mvc的有效 [英] Testing ModelState is always valid in asp.net mvc

查看:229
本文介绍了测试的ModelState总是在asp.net mvc的有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在测试我的控制器行动的ModelState始终有效。

When testing my controller's actions the ModelState is always valid.

public class Product
{
    public int Id { get; set; }

    [Required]
    [StringLength(10)]
    public string Name { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    public decimal Price { get; set; }
}

和我的控制器。

public class ProductController : Controller
{
      [HttpPost]
      public ActionResult Create(Product product)
      {
            if (ModelState.IsValid)
            {
                   // Do some creating logic...
                   return RedirectToAction("Display");
            }

             return View(product);              
      }
 }

和测试:

[Test]
public TestInvalidProduct()
{
     var product = new Product();
     var controller = new ProductController();
     controller.Create(product);
     //controller.ModelState.IsValid == true
}

为什么ModelState中是有效的,当产品不具有名称,描述和价格是多少?

Why the modelState is valid when the product doesn't have a name, Description and price?

推荐答案

在已发布的数据绑定到视图模型验证情况。然后视图模型被传递到控制器。您跳过第1部分和直传球视图模型到控制器中。

Validation happens when the posted data is bound to the view model. The view model is then passed into the controller. You are skipping part 1 and passing a view model straight into a controller.

您可以用手动验证视图模型

You can manually validate a view model using

System.ComponentModel.DataAnnotations.Validator.TryValidateObject()

这篇关于测试的ModelState总是在asp.net mvc的有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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