我的 cshtml 页面在浏览器上将验证消息显示为 json 文本,我缺少什么?
如果我使用属性进行验证,它可以正常工作并在表单字段下方显示错误消息。
如果我使用 IValidatableObject,它会显示为 JSON。 例子:
{"TargetedMemberIds":["Error on ids: \"idwitherror\""]}
谢谢!
我希望 ValidationResult 显示在表单字段下方和/或 ValidationSummary 上
这是您可以遵循的完整工作演示:
型号
public class YourModel : IValidatableObject
{
public string TargetedMemberIds { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(TargetedMemberIds))
{
yield return new ValidationResult("TargetedMemberIds cannot be empty", new[] { nameof(TargetedMemberIds) });
}
// Custom validation logic for specific members
if (TargetedMemberIds == "idwitherror")
{
yield return new ValidationResult("Error on ids: \"idwitherror\"", new[] { nameof(TargetedMemberIds) });
}
}
}
查看
@model YourModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<form asp-action="YourAction">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<!-- Form fields -->
<div class="form-group">
<label asp-for="TargetedMemberIds" class="control-label"></label>
<input asp-for="TargetedMemberIds" class="form-control" />
<span asp-validation-for="TargetedMemberIds" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
控制器
[HttpPost]
public IActionResult YourAction(YourModel model)
{
if (!ModelState.IsValid)
{
return View("YourViewName",model); // Return the view with the model if validation fails
}
// do your stuff...
}