2009-07-25 32 views
0

當我將'Model'對象(由​​LinqToSQL生成)發佈到控制器時,我可以查詢'ModelState.IsValid',並且如果任何驗證屬性屬性和值不驗證,它將被設置爲'false'。對ASP.NET MVC中的普通對象無效的驗證

但是,如果我發佈我自己的類的自定義對象,即使該類的屬性具有驗證屬性並且給出了錯誤的值,ModelState.IsValid似乎總是返回'true'。

爲什麼這隻適用於DataContext模型對象?這些對象使它們與ModelState.IsValid一起工作,而普通的類不會呢?

如何使它與普通類一起工作?


控制器代碼:

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult LogIn(MyProject.Website.ViewModels.Shared.LogIn model) 
{ 
    if (ModelState.IsValid) 
     return View(model); 

    // ... code to log in the user 
} 

視圖模型代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel.DataAnnotations; 
using MyProject.Website.Validators; 
using System.ComponentModel; 

public class LogIn 
{ 

    public LogInModes LogInMode { get; set; } 

    [Required] 
    [EmailAddress] 
    public string EmailAddress { get; set; } 

    public string Password { get; set; } 

    public bool RememberMe { get; set; } 

    public string ReturnUrl { get; set; } 

} 
+1

我懷疑這不是框架,但沒有一點代碼就很難說出問題所在。 – tvanfosson 2009-07-25 13:06:08

回答

1

您是否已將DataAnnotationsModelBinder設置爲您的Global.asax文件中的Application_Start事件的默認模型活頁夾?

protected void Application_Start() { 
    ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder(); 
} 

Becasue據我所知,System.ComponentModel.DataAnnotations下屬性namescape只與模型綁定工作。

您還可以設置你的模型綁定僅適用於行動:

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult LogIn([ModelBinder(typeof(DataAnnotationsModelBinder))] 
    Yieldbroker.Website.ViewModels.Shared.LogIn model) { 
    //... 
} 

this blog postquestion

0

你不應該只是嘗試,如果(model.IsValid())?

編輯:對不起,需要登錄類繼承像模型。