ASP.NET MVC中如何根据DropdownList选中值禁用提交按钮?
Alright, let's get this sorted out for you. Here's the complete, working implementation to make sure your submit button enables/disables correctly based on the dropdown selection:
Updated View Code
I added a default placeholder option and a Bootstrap class for better styling (feel free to skip the class if you don't need it):
@Html.Label("Select Department :") @Html.DropDownList("GroupId", ViewBag.GroupId as SelectList, "-- Select a Department --", new { @class = "form-control" }) <button type="submit" id="submit" name="submit" class="btn btn-success">Get Report</button>
Controller Code (No Changes Needed)
Your existing controller code is already correct for populating the dropdown:
// Place this in your action method that returns the target view ViewBag.GroupId = new SelectList(db.NGAC_GROUP, "ID", "Name");
Note: Double-check that the ID field in your NGAC_GROUP table has a value of "REGULAR" — if you meant to use the Name field as the dropdown value instead, swap the parameters to new SelectList(db.NGAC_GROUP, "Name", "Name").
Fixed JavaScript Code
I cleaned up the logic, added initialization checks, and simplified the disable/enable flow:
$(document).ready(function () { // Run the check once on page load to set the initial button state updateSubmitButtonState(); // Listen for dropdown selection changes $('#GroupId').on('change', function () { updateSubmitButtonState(); }); // Reusable function to handle button state logic function updateSubmitButtonState() { const selectedValue = $('#GroupId').val(); // Set disabled state directly based on the selected value $('#submit').prop('disabled', selectedValue === "REGULAR"); } });
Key Improvements:
- Initialization Check: The function runs when the page loads, so if the dropdown defaults to
"REGULAR", the button will be disabled immediately (no weird initial state inconsistencies). - Simplified Logic: Instead of separate if/else blocks, we directly set the
disabledproperty to the result of our comparison — cleaner and easier to maintain. - Removed Unnecessary Event: I took out the
inputevent, since dropdowns only need thechangeevent to trigger when a selection is made. - Reusable Function: Wrapping the logic in a function makes it easy to call from multiple places without repeating code.
Don't forget to ensure jQuery is loaded in your project — either via a local file reference or NuGet package, since this code depends on it.
内容的提问来源于stack exchange,提问作者John Clarence Castro

