Return to View of two tables using HomeViewModel?

0

I have the following situation, in my Models folder, I have:

public class HomeViewModel
{


    public HomeViewModel()
    {
        // apenas para garantir que NUNCA seja nulo! Facilica código na view
        PreviewImages = new List<Generico.Dominio.TB_IMAGEN_PERFIL>();
        InitialPreviewConfigImages = new List<Generico.Dominio.TB_IMAGEN_PERFIL>();
        User = new Generico.Dominio.TB_USUARIO();
    }

    //imagem do perfil do usuário 
    public List<Generico.Dominio.TB_IMAGEN_PERFIL> PreviewImages { get; set; }
    public List<Generico.Dominio.TB_IMAGEN_PERFIL> InitialPreviewConfigImages { get; set; }
    public Generico.Dominio.TB_USUARIO User { get; set; }


}

I want to bring the registration option along with the image gallery option: In my view today I have a normal register:

@Generic.domain.TB_USUARY

// registration data in the view

// Photo gallery data in View

In the controller I have:

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        public ActionResult ConsultaCadastroUsuarioCompleto(int id)
        {

            try
            {

                var tbuscar = new UsuarioAplicacao();
                TB_USUARIO  tbtabela = tbuscar.ListarPoId(id);

                var model = new HomeViewModel
                {
                    User = tbtabela,
                    PreviewImages = new List<Generico.Dominio.TB_IMAGEN_PERFIL> {
                    new Generico.Dominio.TB_IMAGEN_PERFIL { Id = 1, Url = Url.Content("~/Content/img/galeriaimagens/sl1.jpg") },
                    new Generico.Dominio.TB_IMAGEN_PERFIL { Id = 2, Url = Url.Content("~/Content/img/galeriaimagens/sl2.jpg") },
                    new Generico.Dominio.TB_IMAGEN_PERFIL { Id = 3, Url = Url.Content("~/Content/img/galeriaimagens/sl3.jpg") },
                    new Generico.Dominio.TB_IMAGEN_PERFIL { Id = 4, Url = Url.Content("~/Content/img/galeriaimagens/sl4.jpg") },
                     },
                    // size será preenchido depois (mas se vier do banco de dados, PREENCHA aqui para evitar perda de performance
                    InitialPreviewConfigImages = new List<Generico.Dominio.TB_IMAGEN_PERFIL> {
                    new Generico.Dominio.TB_IMAGEN_PERFIL { Id = 1, Url = Url.Content("~/Content/img/galeriaimagens/sl1.jpg"), Name = "Food-1.jpg" },
                    new Generico.Dominio.TB_IMAGEN_PERFIL { Id = 2, Url = Url.Content("~/Content/img/galeriaimagens/sl2.jpg"), Name = "Food-2.jpg" },
                    new Generico.Dominio.TB_IMAGEN_PERFIL { Id = 3, Url = Url.Content("~/Content/img/galeriaimagens/sl3.jpg"), Name = "Food-3.jpg" },
                    new Generico.Dominio.TB_IMAGEN_PERFIL { Id = 4, Url = Url.Content("~/Content/img/galeriaimagens/sl4.jpg"), Name = "Food-4.jpg" },
                    }

                };
                FindFileSizes(model.InitialPreviewConfigImages);


                return View(model);

            }
            catch (Exception)
            {
                TempData["Erro"] = "Erro ao Alterar Registro.";
                return RedirectToAction("Index", "CadastroCompletoUsuario");
            }

        }



        private void FindFileSizes(List<TB_IMAGEN_PERFIL> imgs)
        {
            foreach (var img in imgs)
            {
                // é preciso converter o caminho relativo da URL em um caminho físico no servidor
                var serverPath = Server.MapPath(img.Url);
                if (System.IO.File.Exists(serverPath))
                {
                    img.Size = new System.IO.FileInfo(serverPath).Length;
                }
            }
        }
        //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

In UserApplication (); has a method that makes a query bringing the data of 1 user.

In the View I have

@model Project.WebSite.Models.HomeViewModel

I can not access the table anymore, how would it look?

    
asked by anonymous 25.10.2016 / 17:26

1 answer

0

First you would change your view model class to:

public class HomeViewModel
{

    public HomeViewModel()
    {
        // apenas para garantir que NUNCA seja nulo! Facilica código na view
        PreviewImages = new List<Generico.Dominio.TB_IMAGEN_PERFIL>();
        InitialPreviewConfigImages = new List<Generico.Dominio.TB_IMAGEN_PERFIL>();
        TabelaUsuario = new Generico.Dominio.TB_USUARIO();
    }

    //imagem do perfil do usuário 
    public List<Generico.Dominio.TB_IMAGEN_PERFIL> PreviewImages { get; set; }
    public List<Generico.Dominio.TB_IMAGEN_PERFIL> InitialPreviewConfigImages { get; set; }
    // não é necessário ser uma lista, já que é apenas um único usuário
    public Generico.Dominio.TB_USUARIO User { get; set; }
}

And in the controller would assign the result of the search of the user data directly to this variable:

public ActionResult ConsultaCadastroUsuarioCompleto(int id)
{
    //... código anterior continua o mesmo (try, etc.)
    var tbuscar = new UsuarioAplicacao();
    TB_USUARIO usuario = tbuscar.ListarPoId(id);

    var model = new HomeViewModel
    {
        User = usuario,
        PreviewImages = new List<Generico.Dominio.TB_IMAGEN_PERFIL> {
            new Generico.Dominio.TB_IMAGEN_PERFIL { Id = 1, Url = Url.Content("~/Content/img/galeriaimagens/sl1.jpg") },
//etc. o resto do código será idêntico...

View Strongly Tipped (with template)

If you are using a strongly typed model, you access the user data in the view via the Model.User (or other name you create) field. As it is strongly typed, you will even have code completion to make programming easier. Study the syntax .NET Razor to get familiar on how to embed code in the middle of HTML. It's very gratifying. Much more efficient than solutions with PHP, because the syntax is much cleaner, although the concept is pretty much the same.

@model Projeto.WebSite.Models.HomeViewModel
@{
    ViewBag.Title = "Home Page";
}
@* Para exibir o nome do usuário, por exemplo *@
<label>@Model.User.Name</label>
@* Não coloque ; ao final do model.User.Name senão vai ser considerado um ';' do html e não da linguagem *@

Note that the Name property of @Model.User.Name may have another name in its TBUSUARY class, whose code has not been posted (let alone the routine code that actually reads this data from the database)

View with dynamic data (ViewBag)

If you are using ViewBag change the controller to:

//...
var tbuscar = new UsuarioAplicacao();
TB_USUARIO usuario = tbuscar.ListarPoId(id);

var model = new HomeViewModel
//...
// adiciona o model no campo dinâmico Model do ViewBag
ViewBag.Model = model;
// não precisa retornar o model no View() porque estamos usando ViewBag
return View();

To make life easier in the view, create a variable to receive data from the ViewBag template already in type HomeViewModel :

@using Meu.Namespace.Onde.Se.Encontra.HomeViewModel
@{
    ViewBag.Title = "Home Page";
    // estou assumindo 
    var model = ViewBag.Model as HomeViewModel;
}
@* Para exibir o nome do usuário, por exemplo *@
<label>@model.User.Name</label>
@* Não coloque ; ao final do model.User.Name senão vai ser considerado um ';' do html e não da linguagem *@

Note: Replace Meu.Namespace.Onde.Se.Encontra.HomeViewModel with the namespace where the HomeViewModel class is!

    
25.10.2016 / 18:10