2
I have a problem, I would like to popular my Dropdownlistfor with the result of another Dropdownlistfor, for this I am using Ajax and Json, same concept they do when they want the result of State to City.
Model:
public class SegmentMOD
{
public int id { get; set; }
[DisplayName("Segmento")]
public string nome { get; set; }
}
public class SectorMOD
{
public int id { get; set; }
[DisplayName("Setor")]
public string nome { get; set; }
public int segmentId { get; set; }
}
Controller:
OpportunityController: Controller
{
public ActionResult Cadastrar()
{
//Aqui funciona normal, retorna os valores
ViewBag.segmentList = new SelectList(new SegmentREP().ListarTodos(),
"id",
"nome"
);
return View();
}
//vai preencher o Where com o Id do segment
public async Task<JsonResult> CarregarSector(int id)
{
var setor = new SectorREP().ListarTodos().Where(x => x.segmentId ==id);
return Json(setor, JsonRequestBehavior.AllowGet);
}
}
View:
@{
ViewBag.Title = "Cadastrar";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("#segment").change(function () {
listaCidade($(this).val());
});
});
//chamada ajax para a Action ListaCidade
//passando como parâmetro a Estado selecionado
function listaCidade(segmentId) {
//Chamando o metodo do controller para retornar um JSON
$.ajax({
url: '/Opportunity/CarregarSector',
type: 'POST',
data: { id: segmentId },
dataType: 'json',
success: function (result) {
$("#sector").empty();
$(result).each(function () {
//adicionando as opções de acordo com o retorno
$("#sector").append("<option value='" + this.id + "'>" + this.nome + "</option>");
});
},
error: function () {
alert('Erro! Não foi possível carregar os Setores.');
}
});
}
</script>
<h2>Cadastrar</h2>
<div class="col-md-4">
@Html.LabelFor(model => model.segment, htmlAttributes: new { @class = "control-label" })
@Html.DropDownListFor(model => model.segment, (SelectList)ViewBag.segmentList, new { @class = "form-control selectpicker show-tick", data_live_search = "true", id = "segment" })
@Html.ValidationMessageFor(model => model.segment, "", new { @class = "text-danger" })
<select class="form-control" id="sector"></select>
</div>
You have already tested Ajax by calling it manually?
– Leonel Sanches da Silva
How would that be ?
– Rodrigo Borghi
Using this.
– Leonel Sanches da Silva
I’ll try to use the tool more if you have the solution thank you.
– Rodrigo Borghi
So, but I need to know more things in order to be able to answer you. Ajax agreeing is one of them. Then I will look at the rest you put. Just with that I can’t tell you what it is.
– Leonel Sanches da Silva
I’m testing more unsuccessfully I need another alternative, but I’ll try in that time.
– Rodrigo Borghi
Do the following: make JSON return output using GET, not POST. As it is read only what you are doing, avoid putting unnecessary complications.
– Leonel Sanches da Silva
It brings a result like this. Load sector? id=2; I would like to know the result of (result), plus it of the error and executes the error: Function()
– Rodrigo Borghi
Good, then it gives error even. The JS console returns something? The code in ASP.NET gives error?
– Leonel Sanches da Silva
The Asp.net code does not return an error and the JS console only (id=2) does not return anything either.
– Rodrigo Borghi
[Httppost] public Jsonresult Loadable (int id) { Return Json (new Sectorrep().Listings().Where(x => x.segmentId == id); } that return ID(id=2) and to complete my Where, and the result would be that Return(Return Json)above, will this format I am returning this correct ?
– Rodrigo Borghi
I told you to take the test without the [Httppost]. Why it hasn’t been done yet?
– Leonel Sanches da Silva
I Fez, I didn’t know the difference.
– Rodrigo Borghi
Friends, I am in need of help because I don’t have a solution... Thank you all and thank you very much to Gypsy Morrison, for the help so far.
– Rodrigo Borghi
Gypsy, I managed to print the value on the Json screen by passing the ID, in the url in the same hand, now I wanted to take and pass the Dropdownlist ID and pass as parameter of the method to list the sectors, the sucess: of the ajax that error.
– Rodrigo Borghi
You can edit your question and put how the code is until then?
– Leonel Sanches da Silva
Thank you, I managed to solve the problem.
– Rodrigo Borghi