我真的很困惑。我在 ASP.NET Core 2 上有一个 Razor 页面,它有一个名为 SchemaId
的必需属性。我尝试将其标记为 [Required]
、[BindRequired]
和 [Required(AllowEmptyStrings = false)]
,但当我发布时在我的表单中,我看到 SchemaId
是 null
而 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 });
}
}
}
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>
如何让模型验证正常工作?
最佳答案
我想我找到了原因。
在PageModel
中定义的 [BindRequired]
和 [Required]
属性似乎被忽略了。因此,您需要像下面这样验证模型:
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();
}
}
然后在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>
我还没有找到任何提到这个的文档,但是在 Microsoft documentation 中他们还在单独的类中编写验证属性,所以我认为这种行为是意料之中的。
希望这能解决问题。
关于c# - 具有空值的必需字符串属性在 ASP.NET Core 2 Razor 页面中给出 IsValid=true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47118980/