You can send via Viewbag, Viewdata or make a class that contains the information (list, item) to be consumed in your View (ViewModel
)
You can use any of the 3 correctly, for example, load a Dropdownlist is very simple with Viewbag. If you are going to pass many class objects and want to keep all this standard you can use a Viewmodel that represents all these class objects.
But, I prefer to pass all the ways for you to know and use properly ...
Viewbag
public ActionResult View(int id)
{
var objPessoa = new PessoaAplic();
var dadosPessoa = objPessoa.ListarPorId(id);
ViewBag.DadosPessoa = dadosPessoa;
var objContato = new ContatoAplic();
var dadosContato = objContato.ListarPorId(dadosPessoa.IdPessoa);
ViewBag.DadosContato = dadosContato;
return View();
}
Viewdata
public ActionResult View(int id)
{
var objPessoa = new PessoaAplic();
var dadosPessoa = objPessoa.ListarPorId(id);
ViewData.Add("DadosPessoa",dadosPessoa);
var objContato = new ContatoAplic();
var dadosContato = objContato.ListarPorId(dadosPessoa.IdPessoa);
ViewData.Add("DadosContato",dadosContato);
return View();
}
Viewmodel
Class responsible for dealing both information:
public class ViewModel
{
public ViewModel(PessoaAplic pessoa, ContatoAplic contato)
{
Pessoa = pessoa;
Contato = contato;
}
public PessoaAplic Pessoa { get; private set; }
public ContatoAplic Contato { get; private set; }
}
Solution within the Controller
public ActionResult View(int id)
{
var objPessoa = new PessoaAplic();
var dadosPessoa = objPessoa.ListarPorId(id);
var objContato = new ContatoAplic();
var dadosContato = objContato.ListarPorId(dadosPessoa.IdPessoa);
ViewModel viewModel = new ViewModel(dadosPessoa, dadosContato);
return View(viewModel);
}
Views:
Viewbag
@{
Layout = null;
WebApplication2.Models.PessoaAplic Pessoa = (WebApplication2.Models.PessoaAplic)ViewBag.DadosPessoa;
WebApplication2.Models.ContatoAplic Contato = (WebApplication2.Models.ContatoAplic)ViewBag.DadosContato;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View</title>
</head>
<body>
<div>
</div>
</body>
</html>
Viewdata
@{
Layout = null;
WebApplication2.Models.PessoaAplic Pessoa = (WebApplication2.Models.PessoaAplic)ViewData["DadosPessoa"];
WebApplication2.Models.ContatoAplic Contato = (WebApplication2.Models.ContatoAplic)ViewData["DadosContato"];
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View</title>
</head>
<body>
<div>
</div>
</body>
</html>
Viewmodel
@model WebApplication2.Models.ViewModel
@{
Layout = null;
WebApplication2.Models.PessoaAplic Pessoa = Model.Pessoa;
WebApplication2.Models.ContatoAplic Contato = Model.Contato;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View</title>
</head>
<body>
<div>
</div>
</body>
</html>
Really what returns the Listarporid of the two classes ? So the answer is correct your question! (What kind of data do they return)
– Cezar