【问题标题】:Add css classes in Razor conditionally based on Valid state of model根据模型的有效状态有条件地在 Razor 中添加 css 类
【发布时间】:2017-03-21 17:27:38
【问题描述】:

我有相当标准的 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>

如果模型的验证失败,我想在表单组中添加一个“has-error”的 CSS 类。描述失败但我无法计算出语法。
我发现了很多有条件地添加文本但不是基于模型的验证状态的示例。

【问题讨论】:

  • 如果 class="input-validation-error" 无效,框架已经添加了它。只需设置该类的样式即可。

标签: asp.net-mvc-4 razor


【解决方案1】:

这样的事情可以帮助你。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-31
    • 2015-01-29
    • 2022-07-05
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    相关资源
    最近更新 更多