MVC / 引导 - 组中的单选按钮在初始化时未选择

MVC / Bootstrap - Radio Button in group not selecting on initialisation

本文关键字:初始化 选择 单选按钮 引导 MVC      更新时间:2023-09-26

我的 MVC 应用程序中有一个具有红绿灯状态的编辑表单。

当表单最初打开时,"灯"上的复选标记始终设置为"绿色",尽管jQuery代码另有设置。

所有代码都在触发,但它只是没有设置初始状态。

在此简化示例中,如果模型的 AlertLevel 设置为"红色",则"勾号"仍位于"绿色"上

标记

@Html.HiddenFor(model => model.AlertLevel)
<span class="btn-group RAGStatus" data-toggle="buttons">
    <label class="btn btn-success active " style="width:50px; height: 30px">
        <input type="radio" name="ragStatus" id="ragButton_Green" autocomplete="off" value="Green">
        <span class="glyphicon glyphicon-hidden unchecked"></span> <span class="glyphicon glyphicon-ok checked"></span>
    </label>
    <label class="btn btn-warning" style="width:50px; height: 30px">
        <input type="radio" name="ragStatus" id="ragButton_Amber" autocomplete="off" value="Amber">
        <span class="glyphicon glyphicon-hidden unchecked"></span> <span class="glyphicon glyphicon-ok checked"></span>
    </label>
    <label class="btn btn-danger" style="width:50px; height: 30px">
        <input type="radio" name="ragStatus" id="ragButton_Red" autocomplete="off" value="Red">
        <span class="glyphicon glyphicon-hidden unchecked"></span> <span class="glyphicon glyphicon-ok checked"></span>
    </label>
</span>

jQuery

$(function () {
    var status = $("#AlertLevel").val();
    $('#ragButton_' + status).prop("checked", true);
})

public class DeptStatus
{
    public string AlertLevel { get; set; }
}

CSS(用于字形图标显示)

.RAGStatus .checked {
    display: none;
}
.RAGStatus .active .checked {
    display: inline-block;
}
.RAGStatus .active .unchecked {
    display: none;
}

更新

在jQuery函数的后续(从示例中删除)中,如果我这样做var ragStatus = $('input[name=ragStatus]:checked').val();那么它返回"红色"

您不需要依赖jQuery来选择按钮组的初始值,因为Razor将能够为您执行此操作,因此在您的情况下:

<span class="btn-group RAGStatus" data-toggle="buttons">
    <label class="btn btn-success active " style="width:50px; height: 30px">
        @Html.RadioButtonFor(m => m.AlertLevel, "Green", new { autocomplete = "off" })
        <span class="glyphicon glyphicon-hidden unchecked"></span> <span class="glyphicon glyphicon-ok checked"></span>
    </label>
    <label class="btn btn-warning" style="width:50px; height: 30px">
        @Html.RadioButtonFor(m => m.AlertLevel, "Amber", new { autocomplete = "off" })
        <span class="glyphicon glyphicon-hidden unchecked"></span> <span class="glyphicon glyphicon-ok checked"></span>
    </label>
    <label class="btn btn-danger" style="width:50px; height: 30px">
        @Html.RadioButtonFor(m => m.AlertLevel, "Red", new { autocomplete = "off" })
        <span class="glyphicon glyphicon-hidden unchecked"></span> <span class="glyphicon glyphicon-ok checked"></span>
    </label>
</span>

看起来引导程序将active类添加到容器中。

尝试

$(function () {
    var status = $("#AlertLevel").val();
    $('#ragButton_' + status).trigger('click');
})

如果你添加:

$('#ragButton_' + status).attr('checked', 'checked);

由于jQuery的版本,它可能prop函数存在一些问题。