Home > Net >  how to set the selected value in dropdown in update form
how to set the selected value in dropdown in update form

Time:09-28

I want the values I previously selected to be displayed when I enter the update form. I did it with input, but I could not do it with dropdown. Please help me how can I give the selected values to dropdown.

 @foreach (var item in Model){
                                            <td><input class="form-control" type="text" value="@item.Deiscreption" name="Deiscreption" required autocomplete="off" /></td>
                                            <td>

                                                <select class="form-control"  name="ControlState" required autocomplete="off">

                                                    <option value="" default="" selected="">انتخاب کنید</option>
                                                    <option value="1">قرمز</option>
                                                    <option value="2">زرد</option>
                                                    <option value="3">سبز</option>
                                                    <option value="4">سفید</option>

                                                </select>

                                            </td>

}

CodePudding user response:

I want the values I previously selected to be displayed when I enter the update form. I did it with input, but I could not do it with dropdown. Please help me how can I give the selected values to dropdown.

It seems that you would pass data through view model from controller to form view, and then display/set the value for input(s) and dropdown based on the view modal data.

To achieve your requirement, you can refer to the following code snippet.

Store selected value in a hidden field

@foreach (var item in Model)
{
    <tr>
        <td><input class="form-control" type="text" value="@item.Deiscreption" name="Deiscreption" required autocomplete="off" /></td>
        <td>
            <input type="hidden" class="hf_selected_val" value="@item.selectedVal" />
            <select class="form-control" name="ControlState" required autocomplete="off">

                <option value="" default="">انتخاب کنید</option>
                <option value="1">قرمز</option>
                <option value="2">زرد</option>
                <option value="3">سبز</option>
                <option value="4">سفید</option>
            </select>
        </td>
    </tr>
} 

Set selected value for dropdown(s) based on the data stored in hidden field

<script>
    $(function () {
        $("select[name='ControlState']").each(function () {
            var selectedVal = $(this).prev("input[type='hidden']").val();
            if (selectedVal != "") {
                $(this).val(selectedVal);
            }
        })
    })
</script>

Test Result

enter image description here

  • Related