根据模型的有效状态有条件地在Razor中添加css类

时间:2017-03-21 17:27:39

标签: asp.net-mvc-4 razor

我有非常标准的MVC Razor代码

    <div class="form-group">
        @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-8 ">
            @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
        </div>
    </div>

如果对model.Description的验证失败但我无法解决语法问题,我想在表单组中添加一个CSS类“has-error”。
我发现了很多有条件地添加文本的例子,但没有基于模型的验证状态。

1 个答案:

答案 0 :(得分:2)

这样的事情可以帮助你。

<script type="text/javascript">
    var isValid = @Html.Raw(Json.Encode(ViewData.ModelState.IsValid));
    if (isValid != 'true') {
        $('.form-selector').addClass('has-error');
    }
</script>