MVC多个ViewModel和ModelState

时间:2014-02-14 21:59:39

标签: asp.net-mvc validation model modelstate

我有两个简单的模型Model1,Model2如下:

public class Model1
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
}
public class Model2
{
    public int Id { get; set; }
    [Required]
    public string Code { get; set; }
}

我有一个BigModel包含另外两个模型:

public class BigModel 
{
    public BigModel()
    {
        Model1 = new Model1 ();
        Model2 = new Model2();
    }
    public Model1 Model1 { get; set; }
    public Model2 Model2 { get; set; }
}

并在我的控制器中:

public ActionResult Register(BigModel bigModel)
    {            
        if (ModelState.IsValid)
        {
            //do somthing
            return RedirectToAction("Index");
        }            
        return View(bigModel);
    }

我的问题是为什么ModelState.IsValid总是如此?虽然设置了数据注释。如何在一个操作中验证两个模型?

1 个答案:

答案 0 :(得分:1)

请不要使用上述方法。始终尝试将ViewModel与您的视图一起使用。在ViewModel上输入所有数据注释,并检查操作方法内部。

请参阅下面提到的示例ViewModel作为示例。

 public class ProductViewModel
    {
        public Guid Id { get; set; }

        [Required(ErrorMessage = "required")]
        public string ProductName { get; set; }

        public int SelectedValue { get; set; }

        public virtual ProductCategory ProductCategory { get; set; }

        [DisplayName("Product Category")]
        public virtual ICollection<ProductCategory> ProductCategories { get; set; }
    }

操作方法内:

        [HttpPost]
        public ActionResult AddProduct(ProductViewModel productViewModel) //save entered data
        {
            //get product category for selected drop down list value
            var prodcutCategory = Repository.GetProductCategory(productViewModel.SelectedValue);

            //for get all product categories
       var prodcutCategories = Repository.GetAllProductCategories();

            //for fill the drop down list when validation fails 
             productViewModel.ProductCategories = prodcutCategories;

            //for initialize Product domain model
            var productObj = new Product
                                     {
                                         ProductName = productViewModel.ProductName,
                                         ProductCategory = prodcutCategory,
                                     };

            if (ModelState.IsValid) //check for any validation errors
            {
                //save recived data into database
                Repository.AddProduct(productObj);
                return RedirectToAction("AddProduct");
            }
            else
            {
                //when validation failed return viewmodel back to UI (View) 
                return View(productViewModel);
            }
        }

注意:我已经写了一篇关于此的文章。请阅读以获取更多信息。

How to Use ViewModel with ASP.NET MVC ?