使用Bootstrap3为Html.ValidationMessageFor设置样式

时间:2016-02-24 12:53:13

标签: html css twitter-bootstrap razor asp.net-mvc-5

我尝试使用Bootstrap 3设置@HTML.ValidationMessageFor元素的样式但不应用CSS。咨询Bootstrap's documentation时,请说明:

要使用,请将.has-warning,.has-error或.has-success添加到父元素。该元素中的任何.control-label,.form-control和.help-block都将收到验证样式。

即使在如上所述嵌套所需的@Html.ValidationMessageFor之后,也没有应用样式:

ValidationMessageForError

请参阅下面的代码段:

模型属性:

[Range(0, int.MaxValue, ErrorMessage = "Client ID cannot be larger than 2147483647.")]
[RegularExpression(@"^[0-9]+$", ErrorMessage = "Client ID must be a positive number.")]
public int searchClientID { get; set; }

查看:

<div class="form-group col-sm-4">
    <div class="input-group">
        <span class="input-group-addon" id="client-ID">Client ID</span>
        @Html.TextBoxFor(m => m.searchClientID, new { @class = "form-control" })
    </div>
    <div class="has-error">
        @Html.ValidationMessageFor(m => m.searchClientID, null, new { @class = "has-error" })
    </div>
</div>

用答案编辑:

<div class="has-error">
    @Html.ValidationMessageFor(m => m.searchClientName, String.Empty, new { @class = "help-block" })
</div>

1 个答案:

答案 0 :(得分:4)

请勿使用form-group替换has-error。我最近使用了与此类似的内容并尝试以下标记。

            <div class="form-group has-error">
                <div >
                    @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
                </div>
                @Html.LabelFor(m => m.ConfirmPassword, new { @class = "control-label" })
                @Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { @class = "help-block" })


            </div>