Return to View two tables using Homeviewmodel?

Asked

Viewed 347 times

0

I have the next 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: On my view today I have a normal record:

@model Generic.Dominio.TB_USUARIO

//view registration data

//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 Usersapplication(); has a method that makes a query bringing the data of 1 user.

in View I have

@model Design.WebSite.Models.Homeviewmodel

But I can’t access the table, how would that look?

  • Put the list code by Id and also the code of the tbuscar.ListarTodos(); to be able to see how the data is coming from the database, because it will be necessary to manipulate them to return in the format that your views expect the data.

  • It would also modify your viewmodel to not have a list of user data, but only the data of a user: instead of public List<Generico.Dominio.TB_USUARIO> TabelaUsuario { get; set; } I would do public Generico.Dominio.TB_USUARIO TabelaUsuario { get; set; } ... actually I would create another User class only with the data pertinent to the view... but this is not so important in your case as you are not sending it via JSON, since you are only dealing with it on the server...

1 answer

0

First it would change its 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 search result 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 Typed (with model)

If you’re using a heavily typed model, you access user data in the view via the field Model.User (or another name you create). As it is strongly typed, you will have, including code completion to facilitate programming. Study some of the syntax Razor of the . NET to get familiar with how to embed code in the middle of HTML. It’s very rewarding. Much more efficient than solutions with PHP, because the syntax is much cleaner, although the concept is practically 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 property Name of @Model.User.Name may have another name in its TBUSUARIO class, whose code has not been posted (much less the routine code that effectively reads this database data)

View with dynamic data (Viewbag)

If you’re 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 already in the 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 by the namespace where the Homeviewmodel class is!

  • I tweaked the code and posted it on the question, but I can’t get the data in the view, thank you

  • @itasouza I have shown how to access the data in the View with the @model Projeto.WebSite.Models.HomeViewModel (strongly typed). Just use @Model.User that will access the data placed in User. But the ideal was that you put the code of the routine that takes the user data. This routine may be in trouble and returning null! I will update the code to give the heavily typed example tb of using the view

Browser other questions tagged

You are not signed in. Login or sign up in order to post.