Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

328
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

you can try this

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda