在页面模型中使用 Razor 页面注释

Using razor pages annotations in page model

我一直在很好地使用数据注释,但是我现在正试图在页面模型中直接指定一个。通常我会创建一个对象模型并在那里指定验证要求,但是由于这只是一个字符串,所以我没有看到这一点。

在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>

不幸的是,表单在为空时提交正常,不会抛出验证错误。

忘了补充:

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

有时候你只需要第二双眼睛:)