我正在使用 ASP MVC 3 制作表单,我不仅是 Web 开发的新手,也是 ASP.NET MVC 的新手。
用户将有机会从下拉菜单中选择一个给定的问题,或者编写自己的问题。
我想做的是阻止用户输入问题的文本字段,以防用户之前从下拉菜单中选择任何问题。
我可以使用 JavaScript 或使用 MVC(我更喜欢使用 MVC 代码,但 JavaScript 也可以)。
<tr>
<td width="40%" height="31">
<div align="right"><strong>Security question:</strong></div>
</td>
<td width="60%" height="31">
@Html.DropDownListFor(m => m.PickSecretQuestion, new[] {
new SelectListItem() { Text = "---select a question --- or create your own below --", Value = "createNew"},
new SelectListItem() { Text = "Mother's Maiden Name?", Value = "Mother's Maiden Name?"},
new SelectListItem() { Text = "Father's Middle Name?", Value = "Father's Middle Name?"},
new SelectListItem() { Text = "What High School did you attend?", Value = "What High School did you attend?"},
new SelectListItem() { Text = "First company you worked for?", Value = "First company you worked for?"}
}
</td>
</tr>
<tr>
<td width="40%" height="31">
<div align="right"><strong>Or create one here:</strong></div>
</td>
<td width="60%" height="31">
@Html.TextBoxFor(m => m.SecretQuestion)
<span style="color:Red"> @Html.ValidationMessageFor(m => m.SecretQuestion </span>
</td>
</tr>
请您参考如下方法:
使用 jQuery 这绝对容易得多。以下是我的处理方式:
$('#yourDropDownId').change(function() {
if ($(this).attr('selectedIndex') == 0)
$('#yourTextBoxId').attr('disabled', 'disabled');
else
$('#yourTextBoxId').removeAttr('disabled');
});
这是真正应该在客户端 上处理的逻辑,而不是前往服务器。利用 jQuery 的强大功能和简单性 绝对有意义。
在您的 View 中,您可以使用辅助方法的 htmlAttributes 对象为您的 DOM 元素设置 id。下面是您要对 TextBoxFor() 所做的更改。这会将您的 id 设置为“yourTextBoxId”。
@Html.TextBoxFor(m => m.SecretQuestion, new { id = "yourTextBoxId" })
