【问题标题】:call MVC Validator in a get method在 get 方法中调用 MVC Validator
【发布时间】:2014-05-23 11:15:38
【问题描述】:

在我的 Controller 中,在 get 方法中,我使用来自查询字符串的元素创建了 My viewModel。 我需要在 MyViewModel 中验证电子邮件,如何调用我的验证器 [EmailValidator]??

 public ActionResult Index(string countryCode)
    {
        var loginViewModel = _loginViewModelFactory.GetLoginViewModel();
        if (**ifvalid(loginViewModel.Mail**))
        {
            _loginViewModelFactory.mail=string.empty;
        }
        return View(loginViewModel);
    }

这是我的模型:

  public class LoginViewModel
    {
        [MailValidator]
        public string Mail { get; set; }
        public string Password { get; set; }
}

【问题讨论】:

  • 您想向电子邮件字段添加验证吗?
  • 我有一个验证器,但我需要在 get 方法中调用它:当电子邮件字段无效时,我将字段的值更改为 string.empty
  • 使用这个link

标签: asp.net-mvc asp.net-mvc-4 validation data-annotations


【解决方案1】:

试试这个

public ActionResult Index(string countryCode)
{
    var loginViewModel = _loginViewModelFactory.GetLoginViewModel();
    ModelState.Clear();
    TryValidateModel(loginViewModel)
    if (ModelState["Mail"].Errors.Any())
    {
        _loginViewModelFactory.mail=string.empty;
    }
    return View(loginViewModel);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 2010-11-29
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多