2011-01-24 41 views
0

我實現了一個自定義成員資格提供者和有下面的類;的ModelState在自定義成員資格提供

public class ProfileCommon : ProfileBase 
{ 
    #region Members 
    [Required(ErrorMessage="Required")] 
    public virtual string Title 
    { 
     get { return ((string)(this.GetPropertyValue("Title"))); } 
     set { this.SetPropertyValue("Title", value); } 
    } 

然後,我在我的控制器想要做以下;

[HttpPost] 
    [Authorize] 
    public ActionResult EditInvestorRegistration(FormCollection collection) 
    { 
     ProfileCommon profileCommon= new ProfileCommon(); 
     TryUpdateModel(profileCommon); 

當有標題不包含在錯誤中時,有點失敗;

對象'Models.ProfileCommon'的屬性存取器'標題'拋出以下異常:'未找到設置屬性'標題'。

如果我擺脫了屬性[Required...它工作正常,但現在我不再有自動驗證我的對象。

現在,我知道我可以在同一時間檢查每個屬性和解決這個問題,但還是我深深地喜歡用DataAnnotations做的工作對我來說。

任何想法?

回答

1

這似乎很奇怪,你正在使用自定義配置文件類作爲行動的輸入,而不是一個視圖模型:

public class ProfileViewModel 
{ 
    [Required] 
    public string Title { get; set; } 
} 

,然後在你的控制器,你可以使用AutoMapper到視圖模型和模型類之間進行轉換這將更新配置文件:

[HttpPost] 
[Authorize] 
public ActionResult EditInvestorRegistration(ProfileViewModel profileViewModel) 
{ 
    ProfileCommon profileCommon = AutoMapper.Map<ProfileViewModel, ProfileCommon>(profileViewModel); 
    ... 
} 
+0

我認爲你的權利。我會移動到視圖模型來代替。謝謝 – griegs 2011-01-24 21:37:51

相關問題