【发布时间】:2016-03-10 12:15:23
【问题描述】:
我的 MVC 应用程序中有一个具有交通灯状态的编辑表单。
最初打开表单时,“灯”上的复选标记始终设置为“绿色”,尽管 jQuery 代码设置了其他设置。
所有代码都在触发,但它只是没有设置初始状态。
在这个简化的例子中,如果 Model 的 AlertLevel 设置为“Red”,“tick”仍然在“green”上
标记
@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();,那么它会返回“Red”
【问题讨论】:
-
你的意思是
AlertLevel在视图加载的时候有值但是加载的时候没有选中对应的单选按钮? -
您的编辑意味着设置
checked属性的脚本正在运行(尽管您的脚本是不必要的,但您使用@Html.RadioButtonFor()方法生成html)。我认为这是<span>元素和/或 css 的问题
标签: javascript jquery css asp.net-mvc razor