MVC2 DataAnnotations on ViewModel - Don't understand using it with MVVM pattern
        Posted  
        
            by ScottSEA
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by ScottSEA
        
        
        
        Published on 2010-06-08T20:20:58Z
        Indexed on 
            2010/06/15
            23:42 UTC
        
        
        Read the original article
        Hit count: 348
        
I have an MVC2 Application that uses MVVM pattern. I am trying use Data Annotations to validate form input.
In my ThingsController I have two methods:
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult Details(ThingsViewModel tvm)
    {
    if (!ModelState.IsValid) return View(tvm);
        try
        {
Query q = new Query(tvm.Query);
            ThingRepository repository = new ThingRepository(q);
tvm.Things = repository.All();                
return View(tvm);
        }
        catch (Exception)
        {
            return View();
        }
    }
My Details.aspx view is strongly typed to the ThingsViewModel:
<%@ Page Title="" 
         Language="C#" 
         MasterPageFile="~/Views/Shared/Site.Master"        
         Inherits="System.Web.Mvc.ViewPage<Config.Web.Models.ThingsViewModel>" %>
The ViewModel is a class consisting of a IList of returned Thing objects and the Query string (which is submitted on the form) and has the Required data annotation:
public class ThingsViewModel
{
    public IList<Thing> Things{ get; set; }
    [Required(ErrorMessage="You must enter a query")]
    public string Query { get; set; }
}
When I run this, and click the submit button on the form without entering a value I get a YSOD with the following error:
The model item passed into the dictionary is of type 
'Config.Web.Models.ThingsViewModel', but this dictionary 
requires a model item of type 
System.Collections.Generic.IEnumerable`1[Config.Domain.Entities.Thing]'.
How can I get Data Annotations to work with a ViewModel? I cannot see what I'm missing or where I'm going wrong - the VM was working just fine before I started mucking around with validation.
© Stack Overflow or respective owner