I have a form in an ASP.NET MVC project, in which when writing a code in an input and at the time of writing it, it should look for that code in a database table and fill a dropdownlist, but the dropdownlist does not fill Here my code:
//Lista de campos
public JsonResult GetCamposList(string Codigo)
{
bd.Configuration.ProxyCreationEnabled = false;
List<TblCampos> ListCampos = bd.TblCampos.Where(x => x.Codigo == Codigo).ToList();
return Json(ListCampos, JsonRequestBehavior.AllowGet);
}
<script type="text/javascript">
$(document).ready(function () {
$("#Codigo").change(function () {
$.get("Solicitud/GetCamposList", { Codigo: $("#Codigo").val() }, function (data) {
$("#Codigo").empty();
$.each(data, function (index, row) {
$("#Codigo").append("<option value='" + row.Cod_Campo + "'>'"+row.Descripcion+"'</option>")
});
});
});
});
</script>
<div class="form-group">
<div class="m-0 font-weight-bold text-primary subtitulo">Codigo:</div>
<input type="text" class="form-control" id="Codigo" name="Codigo" maxlength="5" minlength="5" required=""> @Html.ValidationMessageFor(model => model.Codigo, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<div class="m-0 font-weight-bold text-primary subtitulo">Campo:</div>
<div class="col-md-5">
@Html.DropDownListFor(model => model.Cod_Campo, new SelectList(" "), "--Seleccione un campo--",new { @class="form-control"})
</div>
</div>
Model
public partial class ProdMuestreo
{
public int Id { get; set; }
public string Codigo { get; set; }
public Nullable<int> Cod_Campo { get; set; }
public string Ubicacion { get; set; }
public string Telefono { get; set; }
public List<TblCampos> Campos { get; set; }
}
//ListCampos
public partial class TblCampos
{
public short Cod_Empresa { get; set; }
public string Codigo { get; set; }
public short Cod_Campo { get; set; }
public string Descripcion { get; set; }
}
data example
Tabla ProdMuestreo
Id 0
Codigo 00050
Cod_Campo 1
Ubicacion Mexico
Telefono 55555555
Tabla Campos
Cod_Empresa 1
Codigo 00050
Cod_Campo 1
Descripcion Los Girasoles
The problem is that you try to append to the same input, to correct this problem first assign an Id to your dropdownlist, and then append it, you weren't that far from the solution, your code would look like this: