我一直在使用数据注释,但是现在我试图直接在页面模型中指定一个。通常,我会创建一个对象模型并在其中指定验证要求,但是由于这只是一个字符串,所以我没有意识到这一点。
在card.cshtml.cs
中 public class CardModel : PageModel
{
[BindProperty, StringLength(200, MinimumLength=5, ErrorMessage = "Please enter a note")]
public String Note { get; set; }
public async Task<IActionResult> OnPostNoteAsync(int? id)
{
//Do stuff
return RedirectToPage(new { ID });
}
在card.cshtml中:
<div class="justify-content-center">
<form asp-page-handler="note" method="post">
<input type="hidden" name="id" value=@Model.Card.Id />
<div class="form-group">
<label asp-for="Note" class="control-label">
<i class="fas fa-1x fa-comment-dots pr-2"></i>
New Note
</label>
<textarea asp-for="Note" class="form-control" rows="3"></textarea>
<span asp-validation-for="Note" class="text-danger"></span>
</div>
<div class="form-group" id="card-form" style="text-align: right">
<button type="submit" class="btn btn-ver-blue">
<span class="text">Add Note</span>
</button>
</div>
</form>
</div>
不幸的是,表单为空时提交的很好,没有抛出验证错误。
答案 0 :(得分:0)
忘记添加:
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
有时候您只需要第二双眼睛即可:)