Home > Software engineering >  How to automatically select value from drop down list in asp.net core mvc using jquery or javascript
How to automatically select value from drop down list in asp.net core mvc using jquery or javascript

Time:12-28

The method here is not working.

Here is my cshtml:


    <div >
                                            <label for="inputState">City</label>
                                            <select id="City"  asp-for="City" asp-items="@(new SelectList(ViewBag.Cities,"Id","ZoneName"))" readonly="@(Model.IsView ? true : false)">
                                                <option value="0" selected>Select</option>
                                            </select>
                                        </div>

Jquery

 $("#CustomerName").change(function () {
            var CustomerName = $("#CustomerName").val();
            $.ajax({
                    url: "../Ticket/FetchCustomerAddress",
                    data: { userId: CustomerName },
                    type: "Get",
                    success: function (data) {
                        
                        alert(data.city);
                        //debugger;
                        $('#City').val(data.city);
                    },
                    error: function (err) {
                        //console.error(err)
                        //alert("Internal server error.");
                    }
                });

I am populating the list with the cities. I want to automatically select the city in the list getting from data.city

CodePudding user response:

ASP generate new Id's for your inputs in client side ,

So you select html would look like

<select ID="City"  asp-for="City" asp-items="@(new SelectList(ViewBag.Cities,"Id","ZoneName"))" readonly="@(Model.IsView ? true : false)">
     <option value="0" selected>Select</option>
</select>

the generated id for this is : City.ClientID , so in order to access this selected , you js code should look like

...
success: function (data) {
                        
  alert(data.city);
  //debugger;
  $("#<%=City.ClientID%>").val(data.city);

},
...

note the $("#<%=City.ClientID%>") --> is new generated id would be printed in selector

CodePudding user response:

you can try this

 $("#City option[value=data.city]").attr('selected', 'selected');
  • Related