MVC3根据下拉菜单上的选项锁定文本框
我正在使用ASP MVC 3创建一个表单,我不仅是Web开发的新手,也是ASP.NET MVC的新手。
用户将有机会从下拉菜单中选择一个给定的问题,或者自己编写。
我想要做的是阻止用户输入问题的文本字段,以防用户先前从下拉菜单中选择任何问题。
我可以使用JavaScript或使用MVC(我最好使用MVC代码,但JavaScript也可以使用)。
Security question: @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?"} } Or create one here: @Html.TextBoxFor(m => m.SecretQuestion) @Html.ValidationMessageFor(m => m.SecretQuestion
使用jQuery肯定会更容易 。 这是我如何做到这一点:
$('#yourDropDownId').change(function() { if ($(this).attr('selectedIndex') == 0) $('#yourTextBoxId').attr('disabled', 'disabled'); else $('#yourTextBoxId').removeAttr('disabled'); });
这是真正应该在客户端上处理而不是去服务器的逻辑。 利用jQuery的强大function和简洁性绝对是有意义的 。
在View中,您可以使用htmlAttributes
对象为辅助方法设置DOM元素的id
。 这是您对TextBoxFor()
所做的更改。 这会将您的id
设置为“yourTextBoxId”。
@Html.TextBoxFor(m => m.SecretQuestion, new { id = "yourTextBoxId" })