如果字段有效,如何检查剃刀视图?

How to check in razor view if field is valid?

我将 bootstrap 与 ASP.NET 核心一起使用,并指示表单字段验证错误我想将 has-errors class 添加到 form-group div 当给定字段有错误时。视图看起来像这样:

<div class="form-group">
    <label asp-for="Fragment.Content" class="col-lg-2 control-label "></label>
    <div class="col-lg-10">
        <textarea asp-for="Fragment.Content" class="form-control content-editor"></textarea> 
        <span class="help-block">A longer block of help text that breaks onto a new line and may extend beyond one line.</span>
        <span asp-validation-for="Fragment.Content"></span>
    </div>
</div>

我想做这样的事情:

<div class="form-group" asp-add-class-if-error="has-errors" for-field="Fragment.Content"/>

我知道我可以编写自己的标签助手,但是我很好奇是否有内置的解决方案。

我发现你可以使用:

@using Microsoft.AspNetCore.Mvc.ModelBinding

@if(ViewData.ModelState.GetFieldValidationState("Fragment.Content") == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid)
{
    //  something here
}