I followed some codes that I found here on how to populate a selectbox, but it is not working, is something missing? I'm getting a list of data with my Controller.
JavaScript
$(document).ready(function () {
$(document).select(function () {
$.ajax({
type: 'POST',
url: "/Empresas/SelecionarEmpresas",
data: { empresa: $("#empresa").val() },
dataType: "json",
success: function (json) {
var options = $('#empresa');
options.find('option').remove();
$.each(json, function (key, value) {
$('<option').val(value.IdEmpresa).text(value.Nome).appendTo(options);
//options += '<option value="' + key + '">' + value + '</option>';
});
}
});
});
});
View
<div class="form-group">
<label class="col-md-2 control-label">Empresa: </label>
<div class="col-md-6">
<select class="form-control" name="empresa" id="empresa"></select>
</div>
</div>
Controller
public class EmpresasController : Controller { public ActionResult Empresas() { return View(); } [HttpGet] public JsonResult SelecionarEmpresas() { EmpresaBLL bll = new EmpresaBLL(); List lista = bll.SelecionarEmpresa(); return Json(new { lista }, JsonRequestBehavior.AllowGet); }
BLL
public class EmpresaBLL { public List SelecionarEmpresa() { EmpresaDAL dal = new EmpresaDAL(); DataTable dt = dal.SelecionarEmpresa(); List ListaDeEmpresa = new List(); foreach (DataRow dr in dt.Rows) { EmpresaModel emp = new EmpresaModel { IdEmpresa = Convert.ToInt32(dr["IDEMPRESA"]), Nome = dr["NOME"].ToString(), LogoPath = dr["LOGPATH"].ToString() }; ListaDeEmpresa.Add(emp); } return ListaDeEmpresa; }
Model
public class EmpresaModel { public int IdEmpresa { get; set; } public string Nome { get; set; } public string LogoPath { get; set; } }