Bring value Dropdownlist ASP.NET MV5

Asked

Viewed 35 times

1

I’m bringing a dropdown of a table of Physicians in the View and it brings normally, but I want to take the value of it (Selected name) in the jQuery to bring other information after selected.

But every time I select the item and grab the jQuery, it brings the value of the first name of the list and not the name of the selected person.

How should I proceed?

Controler:

public ActionResult Create()
{
    ViewBag.MedicoId = new SelectList(db.Medicos, "Id", "Nome");
    ViewBag.PacienteId = new SelectList(db.Pacientes, "Id", "Nome");
    return View();
}

View to recover data:

<div class="form-group">
    @Html.LabelFor(model => model.MedicoId, "Nome Médico:", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("MedicoId", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.MedicoId, "", new { @class = "text-danger" })
    </div>
</div>

jQuery that takes the selected value in dropdown (that this with problem, only brings the first name of the list, regardless that I change)

$(document).ready(function () {
    var c = $("#MedicoId option:selected").val();
    $("#MedicoId").change(function () {
        console.log(c);
    });
});

1 answer

0


You have to take the amount by the event change of as follows:

function setMedicoValueDiv(value) {
  $("#medico-id-value").text(value);
}
$(document).ready(function() {
  setMedicoValueDiv($("#MedicoId").val());
  $("#MedicoId").change(function() {
    setMedicoValueDiv($(this).val());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="MedicoId" name="MedicoId">
  <option value="1">Valor 1</option>
  <option value="2">Valor 2</option>
  <option value="3">Valor 3</option>
</select>
<span id="medico-id-value"></span>

I mean, you’re doing it wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.