我在我的MVC应用程序中有一个编辑表单,其中包含交通灯状态。
当打开表单时,“灯”上的勾号始终设置为“绿色”,尽管使用jQuery代码可以设置其他状态。
所有的代码都被触发了,但是它只是没有设置初始状态。
在这个简化的示例中,如果Model的AlertLevel设置为“Red”,“勾号”仍然在“绿色”上。
标记
@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();
,它会返回“红色”。
AlertLevel
已经有一个值,但相应的单选按钮在加载时没有被选中? - Garethchecked
属性的脚本正在工作(尽管如果你使用@Html.RadioButtonFor()
方法生成HTML,你的脚本是不必要的)。我猜想这可能与<span>
元素和/或CSS有关。 - user3559349