2012-01-06 44 views
0

我想驗證我的視圖模型在課堂上。ViewModel課堂級驗證

我正在使用actionFilter。我如何使用數據註釋? 以及如何注入Access數據庫?

如果客戶說它已經是我們的客戶,那麼將會發生驗證。

我用行動過濾器,但我想一定有辦法使用DataAnnotation

評論的代碼如下:

public class DadosAssinaturaFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     var model = filterContext.ActionParameters.Values.FirstOrDefault(x => x.GetType() == typeof(DadosAssinatura)) as DadosAssinatura; 
     var modelState = filterContext.Controller.ViewData.ModelState; 
     if (model != null) 
     { 
      var jaSouCliente = modelState.FirstOrDefault(x => x.Key == "JaSouCliente"); 
      if (jaSouCliente.Key != null) // select "Is Clilent" radiobutton ? 
      if (jaSouCliente.Value.Errors.Count > 0) // if so remove the errors of the registration data 
      { 
       modelState.RemoveKeysStartsWith("DadosCliente."); 
       modelState.RemoveKeysStartsWith("DadosAcesso."); 
      } 
      else if (model.JaSouCliente != null && model.JaSouCliente.Value) // else, click in "Is Client" 
      { 
       modelState.RemoveKeysStartsWith("DadosCliente."); //remove 

       modelState.Remove("DadosAcesso.ConfirmaSenha"); //how injec UnitOfWor/Repository? AutoFac? 
       if (unitOfWork.Client.GetClientByUser(model.DadosAcesso.Usuario, model.DadosAcesso.Senha) == null)//user and Password 
       modelState.AddModelError("DadosAcesso.Usuario", "Usuario Nao Encontrado"); 
      } 
      else if (model.DadosCliente.PessoaFisica) // is a company our people? 
      { 
       modelState.Remove("DadosCliente.RazaoSocial"); // remove validate for company name 
       modelState.Remove("DadosCliente.Cnpj"); //the brazilian document of company 
      } 
      else modelState.Remove("DadosCliente.Cpf"); //the brazilian document of people 
     } 

     base.OnActionExecuting(filterContext); 
    } 
} 

public static class ModelStateErros 
{ 

    public static void RemoveKeysStartsWith(this ModelStateDictionary modelStateDictionary, string startsWith) 
    { 
     var keys = modelStateDictionary.Keys.Where(key => key.StartsWith(startsWith)).ToList(); 
     foreach (var variable in keys) 
     { 
      modelStateDictionary.Remove(variable); 
     } 
    } 
} 

對不起我的英語

回答

0

只需在您的ViewModel類實現IValidateableObject (或創建另一個部分類)並完全避免過濾器,並保留您的驗證邏輯與您的ViewModel。

How do I use IValidatableObject?

+0

但我需要刪除錯誤 – 2012-01-06 17:18:41

+0

沒有,如果你只是不出現問題引發錯誤,而不是擔心刪除它們。這個邏輯應該存在於你的視圖模型中(如果它在那裏可用的話),因爲這看起來是特定於VIEW的驗證。 – 2012-01-06 20:53:07