3
I followed some codes I found here of how popular a selectbox, but it is not working, is it missing something ? 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; } }
if you do
console.log(json)
Is there any feedback? How is this return? inside the before each you remove all options, and inside each vc uses a selector that does not exist, and has invalid syntax– Gabriel Rodrigues
Did not return anything... The code before each I deleted, and the inside I need to create the selector
– Marcos Henrique