首页 > 解决方案 > Aspnet Core MVC 验证消息始终可见

问题描述

我正在实现表单验证,我的模型如下所示:

public class Profile
{
    [Required]
    public string Firstname { get; set; }
}

我的观点是这样的:

<form asp-action="SaveProfile" asp-controller="User" asp- profile="@Model" asp-file="file" enctype="multipart/form-data" method="POST">
    <label asp-for="Firstname">Firstname</label>
    <input class="form-control" id="firstname" asp-for="Firstname" placeholder="Firstname">
    <span asp-validation-for="Firstname"></span>
    <input class="form-control" type="submit" value="Save">
</form>

我的控制器:

public async Task<IActionResult> Index(Profile profile)
{   
    return View(await _userRepository.ReadProfile(User.Identity.Name));
}

ReadProfile()

public async Task<Profile> ReadProfile(string user)
{
    var profile = await _context.User
                    .Where(u => u.Email == user)
                    .Include(s => s.Schedule)
                    .Include(s => s.Skills)
                    .FirstOrDefaultAsync() ?? await CreateProfile(user);
    var schedule = profile.Schedule.OrderBy(sd => sd.StartDate).ToList();
    profile.Schedule = schedule;

    return profile;

}

当我加载视图时,Firstname is required即使该字段包含提交数据,我也会看到

有任何想法吗?

标签: asp.net-mvcvalidationrazorasp.net-core

解决方案


推荐阅读