【问题标题】:MVC2 DataAnnotations on ViewModel - Don't understand using it with MVVM patternViewModel 上的 MVC2 DataAnnotations - 不明白将它与 MVVM 模式一起使用
【发布时间】:2010-06-08 20:20:58
【问题描述】:

我有一个使用 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 视图被强类型化到 ThingsViewModel:

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

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

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 工作正常。

【问题讨论】:

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


    【解决方案1】:

    我认为问题不在于验证。

    改变这一行;

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

    到这里

    tvm.Things = repository.ToList();
    

    我不知道这是什么或它的作用;

    new ThingRepository(q);
    

    它接受一个字符串参数并返回某种Linq IQueriable 或List?如果这返回了其他内容,则可能会导致问题。

    【讨论】:

      【解决方案2】:

      您是否启用了客户端验证?它甚至可能是一个快速的 hacky 修复,但关于错误消息 - 如果没有额外的信息,很难说。你能发布你的视图和渲染的 HTML 吗? 你的详细路线是什么样的? 如果在 Details 方法的开头设置断点,点击提交按钮时是否会命中?

      【讨论】:

        【解决方案3】:

        看起来你可以像这样声明你的 ThingsViewModel:

        public class ThingsViewModel: IEnumerable<Thing>
        

        然后根据需要实现接口以访问事物列表。

        【讨论】:

          【解决方案4】:

          我认为 ASP.NET MVC 可能试图将您的视图映射到错误的控制器。当您返回视图时,您可能需要指定您尝试使用的视图文件名。

          返回视图(“视图名称”)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-09-02
            • 1970-01-01
            • 2013-01-24
            • 2014-04-11
            • 1970-01-01
            • 2021-12-20
            • 1970-01-01
            相关资源
            最近更新 更多