问题
I am making a form using ASP MVC 3 and I am new not only to web development but to ASP.NET MVC as well.
The user will have the chance to either Pick one of the given questions from a dropdown menu, or write their own.
What I am trying to do, is to block the text field where the user will type a question in case the user previously selected any question from the dropdown menu.
I can use either JavaScript or use MVC (I preferably would like to use MVC code, but JavaScript can work as well).
<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>
回答1:
This is definitely much easier with jQuery. Here's how I'd go about this:
$('#yourDropDownId').change(function() {
if ($(this).attr('selectedIndex') == 0)
$('#yourTextBoxId').attr('disabled', 'disabled');
else
$('#yourTextBoxId').removeAttr('disabled');
});
This is logic that really should be handled on the client instead of making a trip to the server. It definitely makes sense to utilize the power and simplicity of jQuery.
In your View, you can set ids for your DOM elements by using the htmlAttributes object for the helper methods. Here's the change you'd make to your TextBoxFor(). This would set your id to "yourTextBoxId".
@Html.TextBoxFor(m => m.SecretQuestion, new { id = "yourTextBoxId" })
来源:https://stackoverflow.com/questions/9234928/mvc3-lock-textbox-based-on-a-selection-on-a-dropdown-menu