【发布时间】:2010-11-10 06:04:05
【问题描述】:
我有一个用 ASP.NET MVC 编写的网站,我为相关页面设置了一个参数,用于指定前一页是什么。这样做的原因是,当用户从特定页面单击图像时,加载的页面将使用 javascript(尤其是 jQuery)自动检查相应的复选框。
下面是获取和设置参数的代码:
<script type="text/C#" runat="server">
protected string Referrer = string.Empty;
protected override void OnLoad(EventArgs e)
{
try
{
Referrer = Request.UrlReferrer.Segments[2].ToLower();
}
catch (System.Exception)
{
Referrer = string.Empty;
}
base.OnLoad(e);
}
</script>
接下来,这里是复选框的集合:
<div id="interestSelect1" class="interestPad">
<%= Html.CheckBoxFor(model => model.Interests[0])%>
<label for="Interests_0_">Insulation</label>
<%= Html.CheckBoxFor(model => model.Interests[1])%>
<label for="Interests_1_">Windows</label>
<%= Html.CheckBoxFor(model => model.Interests[2])%>
<label for="Interests_2_">Siding</label>
<%= Html.CheckBoxFor(model => model.Interests[3])%>
<label for="Interests_3_">Roofing</label>
</div>
<div class="clear">
</div>
<div id="interestSelect2" class="interestPad">
<%= Html.CheckBoxFor(model => model.Interests[4])%>
<label for="Interests_4_">Gutters/Protection</label>
<%= Html.CheckBoxFor(model => model.Interests[5])%>
<label for="Interests_5_">Patio Doors</label>
</div>
在浏览器中呈现时,每个复选框的外观如下:
<input id="Interests_0_" name="Interests[0]" type="checkbox" value="true" />
<input name="Interests[0]" type="hidden" value="false" />
<label for="Interests_0_">Insulation</label>
这是我正在使用的 javascript,但它不起作用:
<script type="text/javascript">
var ref = '<%= Referrer %>';
$(document).ready(function () {
switch (ref) {
case "insulation":
$('Interests_0_').attr('checked', 'checked');
break;
case "windows":
$('Interests_1_').attr('checked', 'checked');
break;
case "siding":
$('Interests_2_').attr('checked', 'checked');
break;
case "roofing":
$('Interests_3_').attr('checked', 'checked');
break;
case "gutters":
$('Interests_4_').attr('checked', 'checked');
break;
case "patiodoors":
$('Interests_5_').attr('checked', 'checked');
break;
default:
// do nothing, not valid ref
}
});
</script>
我显然做错了什么,谁能指出我正确的方向?
谢谢!
编辑: 看起来另一个 JS 文件位于 MasterPage 上,该文件在我的 JS 块导致复选框未被选中之前被调用。主要问题是忘记了# 标识符。
【问题讨论】:
-
@ajreal - 你的评论对我来说似乎相当模糊。能详细点吗?
-
我的错,$('Interests_0_').attr('checked', 'checked');似乎需要更正为 $('#Interests_0_').attr('checked', 'checked');
标签: jquery asp.net-mvc checkbox