1
I have a model called Client with many attributes and (for simplicity I put here only a few) I thought of creating Viewmodels to simplify the display of data in Views, the problem is that the mapping I’m doing (using the Automapper) doesn’t work.
This is the mapping:
CreateMap<ClienteViewModel, Cliente>()
.ForMember(e => e.IDCliente, v => v.MapFrom(s => s.IDCliente))
.ForMember(e => e.IDCliente, v => v.MapFrom(s => s.EnderecoViewModel.IDCliente))
.ForMember(e => e.IDCliente, v => v.MapFrom(s => s.ContatoViewModel.IDCliente));
This is the Json method that performs the mapping. Note that I am setting the value 1000 for the model.Idclient attribute, but after the mapping is executed the value of modelMapping.Idclient is equal to 0.
public JsonResult ItemClienteAtendimentoHist(ClienteViewModel model)
{
model.IDCliente = 1000;
string mensagem = "";
try
{
var modelMapping = Mapper.Map<ClienteViewModel, Cliente>(model);
var retCliente = _ctx.ObterCliente(modelMapping);
return Json(new { Cliente = retCliente, success = true, message = mensagem }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { message = ex.Message, success = false });
}
}
Viewmodels:
public class ClienteViewModel{
public int IDCliente {get; set;}
public string NomeCliente {get; set;}
public string CPFCliente {get; set;}
public EnderecoViewModel EnderecoViewModel {get; set;}
public ContatoViewModel ContatoViewModel {get; set;}
}
public class EnderecoViewModel{
public int IDCliente {get; set;}
public string LogradouroEndreco {get; set;}
public string NumeroEndereco {get; set;}
public string CEPEndereco {get; set;}
public ClienteViewModel ClienteViewModel {get; set;}
}
public class ContatoViewModel{
public string public int IDCliente {get; set;}
public string NomeContato {get; set;}
public string TelContato {get; set;}
public ClienteViewModel ClienteViewModel {get; set;}
}
Model Cliente:
public class Cliente{
public int IDCliente {get; set;}
public string NomeCliente {get; set;}
public string CPFCliente {get; set;}
public string LogradouroEndreco {get; set;}
public string NumeroEndereco {get; set;}
public string CEPEndereco {get; set;}
public string NomeContato {get; set;}
public string TelContato {get; set;}
}