Search code examples
viewasp.net-core-mvcsetdropdownselected

Set Selected Value in Dropdown


I have 2 dropdown boxes. Based on value selected in first dropdown box 2nd box should get populated. I have no issue with 2nd box getting populated but value of fist box goes missing . I need value of fist box should be as it is.

My code in View is :

     <input type="text" name="medCompany" id="medCompany" list="ddlmedCompany" class="form-control form-control-lg" />
                                    <datalist id="ddlmedCompany">
                                        @foreach (var item in Model.lstmedCompany)
                                        {
                                                <option selected="selected">@item.Text</option>
                                        }
                                    </datalist>
                                

  <input type="text" name="medName" id="medName" list="ddlmedName" class="form-control form-control-lg" />
                                    <datalist id="ddlmedName" >
                                        @foreach (var item in Model.lstmedName)
                                        {
                                            <option>@item.Text</option>
                                        }
                                    </datalist>

<script>
    $(function() {
        $('#medCompany').change(function() {
            window.location = "GetMedicineList?medicine=" + $(this).val();
        });
    });
</script>

My controller code is :

  GetMedList getMedCompanyList = new GetMedList(this._configuration);
        List<SelectListItem> lstMedName = getMedCompanyList.GetMedCompanyCode(medicine);
        addMedicinesViewModel.lstmedName = lstMedName;

        List<SelectListItem> lstMedCompany = getMedCompanyList.GetMedCompanys(medicine);
        addMedicinesViewModel.lstmedCompany = lstMedCompany;            
        addMedicinesViewModel.medCompany = medicine;

        return View("AddMedicine", addMedicinesViewModel);

What should I have to do so that first dropdown value remain intact/display selected value and 2nd dropdown gets populated.


Solution

  • I need value of fist box should be as it is.

    Try to use asp-for="medCompany" in the first dropdown box , like :

    <input type="text" asp-for="medCompany"  list="ddlmedCompany" class="form-control form-control-lg" />