【问题标题】:.NET Core: always showing validation errors.NET Core:总是显示验证错误
【发布时间】:2017-01-13 22:23:05
【问题描述】:

我有简单的登录表单。
除了一件事,一切都很好。当您进入该页面时,它始终显示验证(例如。字段是必需的),即使没有向控制器发布数据。
有没有办法只在实际发出 POST 请求时显示验证?

查看

@model LoginViewModel
<form asp-controller="User" asp-action="Login" method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <label asp-for="Email"></label>
    <input asp-for="Email" />
    <span asp-validation-for="Email"></span>

    <label asp-for="Password"></label>
    <input asp-for="Password" />
    <span asp-validation-for="Password"></span>

    <button type="submit">Login</button>
</form>

视图模型

public class LoginViewModel
{
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

动作

[HttpGet]
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model)
    {
        ClaimsPrincipal userClaims = _userRepository.TryLogin(model);

        if (userClaims != null)
        {
            ...
        }
        return View(model);
    }

【问题讨论】:

标签: c# asp.net-core-mvc


【解决方案1】:

正如 Paul 在 cmets 中提到的那样,您应该删除 [Get] 属性,该属性将阻止对操作的 Get 请求,而是创建一个新的控制器操作来负责处理不会导致操作模型的 get 请求@ 987654322@ 为空。

例如:

[AllowAnonymous]
public async Task<IActionResult> Login()
{
    return View(new LoginViewModel());
}

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model)
{
    ClaimsPrincipal userClaims = _userRepository.TryLogin(model);

    if (userClaims != null)
    {
        ...
    }
    return View(model);
}

现在您的验证只会因无效的帖子模型而触发。

【讨论】:

  • 谢谢!那成功了。我想把它保持在一个动作中,但这种方法至少有效:)
  • 很高兴它有帮助。将命令与查询(从 get 发布)分离通常可以使事情更易于维护。更不用说让一个方法同时处理 post 和 get 会违反单一责任原则。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多