我正在实现表单验证,我的模型如下:
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
有什么想法吗?