具有null值的必需字符串属性在ASP.NET Core 2 Razor Page中提供IsValid = true

Sea*_*ish 5 c# model-validation asp.net-core-mvc asp.net-core

我真的很困惑.我在ASP.NET Core 2上有一个Razor页面,它具有一个必需的属性SchemaId.我试着将其标记为[Required],[BindRequired],和[Required(AllowEmptyStrings = false)],但是当我发表我的形式,我看到SchemaIdnull,但ModelState.IsValid == true.这是Upload.cshtml.cs:

namespace Uploader.Pages
{
    public class UploadModel : PageModel
    {
        private IUploader _uploader;

        public UploadModel(IUploader uploader)
        {
            _uploader = uploader;
        }

        [BindProperty]
        public IEnumerable<IFormFile> UploadedFiles { get; set; }

        [Required(AllowEmptyStrings = false)]
        [BindProperty]
        [BindRequired]
        public string SchemaId { get; set; }


        public void OnGet(string schemaId = null)
        {
            SchemaId = schemaId;
        }

        public async Task<IActionResult> OnPostAsync()
        {
            // SchemaId is NULL right here!
            if (!ModelState.IsValid) // Yet IsValid = true!
            {
                return Page();
            }

            // Use _uploader to actually upload the file

            return RedirectToPage("/Next", new { uploadId = uploadId, schemaId = SchemaId });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Upload.cshtml文件中的相关摘录:

<div asp-validation-summary="All"></div>
<form enctype="multipart/form-data" method="POST" asp-page="Upload">
    <input class="inputfile" type="file" id="UploadedFiles" multiple="multiple" name="UploadedFiles">
    <label for="UploadedFiles">
        <span>Choose a file...</span>
    </label>
    <input type="hidden" asp-for="SchemaId">
    <button type="submit" class="inputfilesubmit">Upload</button>
</form>
Run Code Online (Sandbox Code Playgroud)

如何才能使模型验证正常工作?

Mik*_*Mat 1

我想我找到了原因。

[BindRequired][Required]中定义的属性似乎PageModel被忽略了。因此,您需要验证模型,如下所示:

public class Schema
{
    [Required]
    [BindRequired]
    public string Id { get; set; }
}
public class TestModel : PageModel
{
    [BindProperty]
    public Schema Schema { get; set; }

    public async Task<IActionResult> OnPostAsync()
    {
        // SchemaId is NULL right here!
        if (!ModelState.IsValid) // Yet IsValid = true!
        {
            return Page();
        }

        return Page();
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在cshtml中

<div asp-validation-summary="All"></div>
<form enctype="multipart/form-data" method="POST" asp-page="Upload">
    <input class="inputfile" type="file" id="UploadedFiles" multiple="multiple" name="UploadedFiles">
    <label for="UploadedFiles">
        <span>Choose a file...</span>
    </label>
    <input type="hidden" asp-for="Schema.Id">
    <button type="submit" class="inputfilesubmit">Upload</button>
</form>
Run Code Online (Sandbox Code Playgroud)

我仍然没有找到任何文档提到这一点,但在Microsoft 文档中,他们还在单独的类中编写验证属性,所以我认为这种行为是预期的。

希望这能解决问题。