1
In an address registration form, I’d like to do the following. the guy types the zip code, then searches the zip code, and returns the data to fill in the Editorfor. So far so good, it’s working. City and States are in a separate table, and are displayed by Dropdownlist. Wanted that on the return of Json, the data besides being filled in the Editorfor, also be displayed in the Dropdownlist according to the typed zip code. Ex: Dropdownlist of states is displayed as Select and after typing a cep that for example corresponded to SP the dropdown brought the listed state, instead of remaining the Select
Dropdownlist
<div class="form-group">
@Html.LabelFor(model => model.EstadoID, "Estado", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("EstadoID", null, htmlAttributes: new { @class = "form-control", id = "Estado", })
@Html.ValidationMessageFor(model => model.EstadoID, "", new { @class = "text-danger" })
</div>
</div
Ex of an Editorfor being filled with feedback information:
<div class="form-group">
@Html.LabelFor(model => model.Bairro, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Bairro, new { htmlAttributes = new { @class = "form-control", id = "bairro" } })
@Html.ValidationMessageFor(model => model.Bairro, "", new { @class = "text-danger" })
</div>
</div>
and here, my return object Json:
<script>
$(document).ready(function () {
$("#cep").blur(function () {
var cepValue = $(cep).val();
$.ajax({
type: 'POST',
url: 'RetornaEndereco',
data: { cep: cepValue },
dataType: 'json',
success: function (data) {
$('#bairro').val(data.bairro);
$('#endereco').val(data.end);
$('#cidade').val(data.cidade);
$('#estado').val(data.uf);
},
error: function (data) {
alert('Error' + data);
}
});
});
});
</script>
and finally the Controller:
public JsonResult RetornaEndereco(string cep)
{
var valor = Regex.Replace(cep, "[^0-9]", "");
var ws = new WSCorreios.AtendeClienteClient();
var resposta = ws.consultaCEP(valor);
try
{
System.Console.WriteLine();
System.Console.WriteLine("Endereço: {0}", resposta.end);
System.Console.WriteLine("Bairro: {0}", resposta.bairro);
System.Console.WriteLine("Cidade: {0}", resposta.cidade);
System.Console.WriteLine("Estado: {0}", resposta.uf);
}
catch (Exception ex)
{
return Json("Erro ao efetuar busca do CEP: {0}", ex.Message);
}
//Alterado Daqui pra baixo
Estado estado = (from u in db.Estados where u.Sigla == resposta.uf select u).SingleOrDefault();//Busca no banco pelo Estado
Cidade iDCidade = (from u in db.Cidades where u.Nome == resposta.cidade && u.EstadoID == estado.EstadoID select u).SingleOrDefault();//Busca no banco pela cidade que está no mesmo estado
Cidade levaCidade = new Cidade();
if (iDCidade == null)//Se a cidade não estiver cadastrada, insere uma nova cidade.
{
Cidade cidade = new Cidade();
cidade.Nome = resposta.cidade;
cidade.EstadoID = estado.EstadoID;
db.Cidades.Add(cidade);
db.SaveChanges();
levaCidade.CidadeID = cidade.CidadeID;//Pega o ID da cidade cadastrada
levaCidade.EstadoID = cidade.EstadoID;//pega o id do estado selecionado
}
else
{
Cidade cidade = new Cidade();
cidade.Nome = resposta.cidade;
cidade.EstadoID = estado.EstadoID;
levaCidade.CidadeID = iDCidade.CidadeID;//Pega o ID da cidade cadastrada
levaCidade.EstadoID = estado.EstadoID;//pega o id do estado selecionado
}
Endereco levarEndereco = new Endereco();//Cria o objeto para ser transportado pelo Json
levarEndereco.CidadeID = levaCidade.CidadeID;
levarEndereco.Numero = levaCidade.EstadoID;//Passando o id do estado na variavel numero para alterar no json
levarEndereco.Bairro = resposta.bairro;
levarEndereco.Descricao = resposta.end;
ViewBag.CidadeID = new SelectList(db.Cidades, "CidadeID", "Nome", levarEndereco.CidadeID);
return Json(levarEndereco);
//Alterado até aqui
}
Console Log as @Brunno said:
@Bruno I am doing the data insertion of cities according to the zip code. the guy types a zip code, if the city is not registered in the bank, he inserts, and the return brings the city ID, in case needed to refresh the dropdown.
– Fabio Souza
Cool, so you already had all the cities on the Dropdownlist :) this refresh gave using what ? . change() ?
– Brunno
I don’t think you understand... so, the guy type a zip code, if in my base, that city doesn’t have, he inserts it in my base, and the dropdownlist doesn’t display that value, because I need to give a refresh just on it understood? I’m here looking for an option that only updates it..., if I give a refresh on the full page the dropdown displays the value, if it doesn’t show... know something about this refresh only in a component?
– Fabio Souza
So, the idea of . change() is this, updating your component. would look something like this: $('#status'). val(data.Uf). change(); =]
– Brunno
I did so $('#city'). val(data.Cidadeid). change(); but it updates only if the city has already been loaded in the page load. if it is a new city, which was inserted does not appear during the process it does not appear (only after the refresh)...
– Fabio Souza
Tell me something, when you create a new city as it comes within the date ? the idea of my answer above is that same, if there already exists the . change() will simply update your Dropdownlist, since if it does not exist, you will have to add it to the list. Now enter the question how to add, if you have all the values {name and id}, just add in your same dropdown shown above: $('#city'). append($('<option>', { value: date.city, //city id text: date.city // City name }));
– Brunno
I changed the Controler check it out so you can see.... below the Catch
– Fabio Souza
@Fabiosouza, cleared well now hehe.. next, the Dropdownlist it will be loaded with the Viewbag only when your Action is loaded the first time. we have no way to update it without an ajax :( to get around it I advise you to do the following. You know the class Address you instance it with name take Echo ? I would add an attribute to it with the name of Novacidade for example and send it the name of the new city to add in the Dropdownlist using the way I showed you above.
– Brunno
Another alternative, particularly I find more semantic but less performatic. It would fire an ajax just to update your cities. And after that set the result =]
– Brunno
value 1 would be the ID?
– Fabio Souza
@Fabiosouza, that .. value is the Id, and the text is the text that will display to the user, in this case the name of the city.
– Brunno
@Bruno, if it were a data list, would the append work the same way? or would it be something else ai? a single item it works, more items not...
– Fabio Souza
No, in case you would have to iterate in the list with a foreach and then use the append item by item
– Brunno
Bruno, in case I get the city in Json as you said, but I did not understand how I use the parse, because then you entered fixed values, but in my case will always vary
– Fabio Souza
@Fabiosouza, from a console log on your return from ajax and post on the question to see how it’s coming.
– Brunno
I don’t know if it’s right, because I’m still learning... it’s in the answer.
– Fabio Souza
@Fabiosouza, cool saw your return here :), so I did an update upstairs on the answer and I’ll guide you here, you know where I do JSON.parse() and I pass a string inside ? just take my string and pass your variable that gave console.log(). tmb check the id of your select if it is matching id that is on the selector before the append :)
– Brunno