Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

324
Views
How to automatically select value from drop down list in asp.net core mvc using jquery or javascript?

The method here is not working.

Here is my cshtml:

<div class="form-group col-md-4">
  <label for="inputState">City</label>
  <select id="City" class="form-control basic" 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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

So you select html would look like

<select ID="City" class="form-control basic" 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

about 4 years ago · Juan Pablo Isaza Report

0

you can try this

 $("#City option[value=data.city]").attr('selected', 'selected');
about 4 years ago · Juan Pablo Isaza Report

0

$('#City').val(data.city); is the correct way to set selected value for dropdownlist.

For this constructor: new SelectList(ViewBag.Cities,"Id","ZoneName")), the first parameter is the source, the second parameter is each option value in select, the third parameter is that each option displays text in html.

That is to say, Id represents the option value and ZoneName represents the option text.

When you set the value for select, you need be sure the data.city value equals to any value of Id.

Testing code:

Model:

public class Test
{
    public string City { get; set; }
}
public class City
{
    public int Id { get; set; }
    public string ZoneName { get; set; }
}

View(Index.cshtml):

@model Test
<select id="CustomerName">
    <option>custom1</option>
    <option>custom2</option>
    <option>custom3</option>
</select>
<div class="form-group col-md-4">
    <label for="inputState">City</label>
    <select id="City" class="form-control basic" asp-for="City"
            asp-items="@(new SelectList(ViewBag.Cities,"Id","ZoneName"))">
        <option value="0" selected>Select</option>
    </select>
</div>
@section Scripts
{
<script>
    $("#CustomerName").change(function () {
        var CustomerName = $("#CustomerName").val();

        $.ajax({
            url: "/Home/FetchCustomerAddress",
            data: { userId: CustomerName  },
            type: "Get",
            success: function (data) {
                alert(data.city);    
                $('#City').val(data.city);
            },
            error: function (err) {
                //console.error(err)
                //alert("Internal server error.");
            }
        })
    });
</script>
}

Controller:

public IActionResult Index()
{
    ViewBag.Cities = new List<City>()
    {
        new City(){Id=1,ZoneName="aa"},
        new City(){Id=2,ZoneName="bb"},
        new City(){Id=3,ZoneName="cc"}
    };
    return View();
}

public IActionResult FetchCustomerAddress(string userId)
{
    //do your stuff...
    return Json(new Test() { City = "2" });
}

Render view:

enter image description here

Ajax response data(press F12 in browser -> click Network panel -> choose FetchCustomerAddress method name -> choose Response)

enter image description here

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!