2010-06-08 25 views
3

我有一個MVC2應用程序使用MVVM模式。我正在嘗試使用數據註釋來驗證表單輸入。ViewModel MVC2 DataAnnotations - 不明白與MVVM模式使用它

在我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>" %> 

視圖模型是由返回事的IList中的類對象和查詢字符串(它在表單上提交)並具有所需的數據註釋:

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工作?我看不到我錯過了什麼,或者我錯了什麼地方 - 在我開始驗證之前,虛擬機工作得很好。

回答

1

我不認爲問題與驗證。

更改此行;

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

這個

tvm.Things = repository.ToList(); 

我不知道這是什麼,或者做什麼;

new ThingRepository(q); 

它需要一個字符串參數並返回某種Linq IQueriable或List?如果這是返回別的東西,它可能會導致問題。

0

您是否啓用了客戶端驗證?它甚至可能是一個快速的黑客修復,但關於錯誤信息 - 沒有額外的信息很難說。你可以發佈你的視圖和呈現的Html嗎? 你的細節路線是什麼樣的? 如果你在Details方法的開始處設置了一個斷點,當你點擊提交按鈕時它會被擊中嗎?

0

它看起來像你可以只聲明您ThingsViewModel像這樣:

public class ThingsViewModel: IEnumerable<Thing> 

,然後實現接口酌情訪問列表的事情。

0

我認爲ASP.NET MVC可能試圖將您的視圖映射到錯誤的控制器。當您返回視圖時,您可能需要指定您嘗試使用的視圖文件名。

return View(「ViewName」)

相關問題