c# - ViewModel 上的 MVC2 DataAnnotations - 不理解将它与 MVVM 模式一起使用

标签 c# asp.net-mvc mvvm data-annotations

我有一个使用 MVVM 模式的 MVC2 应用程序。我正在尝试使用数据注释来验证表单输入。

在我的 ThingsController 中,我有两种方法:

    [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();
        }
    }

我的 Details.aspx View 是 ThingsViewModel 的强类型:

<%@ Page Title="" 
         Language="C#" 
         MasterPageFile="~/Views/Shared/Site.Master"        
         Inherits="System.Web.Mvc.ViewPage<Config.Web.Models.ThingsViewModel>" %>

ViewModel 是一个类,由返回的 Thing 对象的 IList 和查询字符串(在表单上提交)组成,并具有 Required 数据注释:

public class ThingsViewModel
{
    public IList<Thing> Things{ get; set; }

    [Required(ErrorMessage="You must enter a query")]
    public string Query { get; set; }
}

当我运行它,并在没有输入值的情况下单击表单上的提交按钮时,我得到一个 YSOD 并显示以下错误:

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]'.

如何让数据注释与 ViewModel 一起工作?我看不出我遗漏了什么或哪里出错了 - 在我开始进行验证之前,VM 工作得很好。

最佳答案

我认为问题不在于验证。

改变这一行;

tvm.Things = repository.All(); //Is this the Linq extension method 'All()'?

对此

tvm.Things = repository.ToList();

我不知道这是什么,也不知道它有什么作用;

new ThingRepository(q);

它接受一个字符串参数并返回某种 Linq IQueriable 或 List?如果返回的是其他内容,则可能是问题所在。

关于c# - ViewModel 上的 MVC2 DataAnnotations - 不理解将它与 MVVM 模式一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3000979/

相关文章:

c# - 接受返回 null 的方法 - C# .NET MVC

c# - 在 C# 中 'where T : class?' 是什么意思

c# - 在逐字字符串文字中进行替换?

c# - WebRequests 很慢(需要 4 秒)我如何加快它们的速度?

c# - 使用 View 模型值的依赖属性

c# - 部分类(class)的目的是什么?

c# - 将 DbContext SaveChanges 与事务一起使用

javascript - .on ('click' ,如果链接在部分 View 内呈现,则不会触发函数(事件)

mvvm - 可移植 View 模型中的MVVM和模态

WPF:MVVM 对转换器说不,但我需要很好的枚举值