2
Answers

MVC How to get disable drop down Value

Hi

 MVC 5

 @Html.DropDownList("DDCA", ViewData["DDCA"] as List<SelectListItem>, "-- Select --", new { @class = "form-control text-center", required = "required" })

i am binding values like this after genrate otp i want to disable this drop down while submit  i am using

@disable="disable" but submition time dtop down value comes null i remove disable drop dwon value i will get but i want to disable and get that value while submission

Answers (2)

1
Photo of Alpesh Maniya
458 3k 157.1k 1y

You may try with below steps 

  1. Add a hidden field to store the selected dropdown value:

    @Html.Hidden("DDCA_SelectedValue", ViewData["DDCA_SelectedValue"] ?? "")

     

  2. Use JavaScript to disable the dropdown and update the hidden field during form submission:
     

    <script>
        function submitForm() {
            var dropdown = document.getElementById("DDCA");
            var hiddenField = document.getElementById("DDCA_SelectedValue");
            dropdown.disabled = true;
            hiddenField.value = dropdown.value;
            document.forms["yourFormName"].submit();
        }
     </script>

     

  3. Modify the submit button to call the JavaScript function:

    <input type="submit" value="Submit" onclick="submitForm();" />

     

This approach ensures that the dropdown is visually disabled for user interaction, but its selected value is still included in the form submission.

1
Photo of Tahir Ansari
253 7.5k 228k 1y

If you want to disable the dropdown during form submission but still receive its selected value, you should use the disabled attribute in the HTML and manage the disabled state using JavaScript or Razor syntax. The @disable="disable" you mentioned seems like a typo; the correct attribute is disabled.

@Html.DropDownList("DDCA", ViewData["DDCA"] as List<SelectListItem>, "-- Select --", new { @class = "form-control text-center", id = "myDropdown" })

<script>
    // JavaScript to disable the dropdown on form submission
    document.getElementById('myDropdown').disabled = true;

    // You can use the onsubmit event of your form to enable the dropdown before submission
    document.getElementById('yourFormId').onsubmit = function () {
        document.getElementById('myDropdown').disabled = false;
    };
</script>
@Html.DropDownList("DDCA", ViewData["DDCA"] as List<SelectListItem>, "-- Select --", new { @class = "form-control text-center", id = "myDropdown" })

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
    // jQuery to disable the dropdown on form submission
    $(document).ready(function () {
        $('#myDropdown').prop('disabled', true);

        // You can use the submit event of your form to enable the dropdown before submission
        $('#yourFormId').submit(function () {
            $('#myDropdown').prop('disabled', false);
        });
    });
</script>