You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC中如何根据DropdownList选中值禁用提交按钮?

Solution to Disable/Enable Submit Button Based on Dropdown Selection in ASP.NET MVC

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 disabled property to the result of our comparison — cleaner and easier to maintain.
  • Removed Unnecessary Event: I took out the input event, since dropdowns only need the change event 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:08:29