【问题标题】:ViewModel class-level validationViewModel 类级验证
【发布时间】:2012-01-06 15:17:17
【问题描述】:

我想在类级别验证我的视图模型。

我正在使用 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);
        }
    }
}

对不起我的英语

【问题讨论】:

    标签: asp.net-mvc-3 repository data-annotations autofac


    【解决方案1】:

    只需在您的 ViewModel 类中实现 IValidateableObject(或创建另一个分部类)并完全避免过滤器,并将您的验证逻辑与您的 ViewModel 保持一致。

    How do I use IValidatableObject?

    【讨论】:

    • 不,如果它是一个问题,你只是不提出错误,而不是担心删除它们。这个逻辑应该存在于您的视图模型中(如果它在那里可用),因为这似乎是特定于 VIEW 的验证。
    猜你喜欢
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    相关资源
    最近更新 更多