Return two models in a view (foreach)

Asked

Viewed 437 times

-1

good morning. I’m new to C# and Asp . net and I ran into a problem. Developing a virtual calendar, I would like to display two queries on a page just when the user logs in, however, there in my controller I can only return a view even having created a layout that receives my two models.

I think the problem is the foreach, I tried the Tuple, but my lists are not that kind...

Any hint is welcome. Hugs.

Follow the controller code:

namespace Projeto.WEB.Controllers
{
    public class LoggedController : Controller
    {
        // GET: Logged
        [Authorize]
        public ActionResult Index()
        {
            List<MasterLayoutModel> listaTAR = new List<MasterLayoutModel>();
            try
            {

                TarefaRepositorio rep = new TarefaRepositorio();
                foreach (Tarefa t in rep.FindAll())
                {
                    MasterLayoutModel mModel = new MasterLayoutModel();
                    ConsultaTarefaModel model = new ConsultaTarefaModel();      
                    UsuarioRepositorio repUsuario = new UsuarioRepositorio();


                    t.Usuario = new Usuario();
                    t.Usuario = repUsuario.FindByLogin(User.Identity.Name);


                    model.IdTarefa = t.IdTarefa;
                    model.Nome = t.Nome;
                    model.DataEntrega = t.DataEntrega;
                    model.Descricao = t.Descricao;

                    mModel.ConsultaTarefaModel = new ConsultaTarefaModel();

                    listaTAR.Add(mModel); //adicionar na lista..


                }
            }
            catch (Exception e)
            {
                //gerar mensagem de erro..
                ViewBag.Mensagem = e.Message;
            }
            //enviando a model..

            List<MasterLayoutModel> listaCTT = new List<MasterLayoutModel>();
            try
            {

                ContatoRepositorio rep = new ContatoRepositorio();
                foreach (Contato c in rep.FindAll())
                {

                    ConsultaContatoModel model = new ConsultaContatoModel();
                    MasterLayoutModel mModel = new MasterLayoutModel();
                    UsuarioRepositorio repUsuario = new UsuarioRepositorio();



                    c.Usuario = new Usuario();
                    c.Usuario = repUsuario.FindByLogin(User.Identity.Name);


                    model.IdContato = c.IdContato;
                    model.Nome = c.Nome;
                    model.Email = c.Email;
                    model.Telefone = c.Telefone;

                    mModel.ConsultaContatoModel = new ConsultaContatoModel();

                    listaCTT.Add(mModel); //adicionar na lista..   


                }
            }
            catch (Exception e)
            {
                //gerar mensagem de erro..
                ViewBag.Mensagem = e.Message;
            }



            return View();                        


        }            


    }
}

Below, I demonstrate the Masterlayoutmodel and cshtml view:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Projeto.WEB.Models;

namespace Projeto.WEB.Models
{
    public class MasterLayoutModel
    {
        public ConsultaTarefaModel ConsultaTarefaModel { set; get; }
        public ConsultaContatoModel ConsultaContatoModel { set; get; }

    }
}

index.cshtml

model List<Projeto.WEB.Models.MasterLayoutModel>


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Templates/Layout.cshtml";
}



<h4>Bem vindo ao Sistema</h4>
<hr />

<div class="row top top-right">
    <div class="col-md-3">
        <div class="panel panel-primary navbar-left">
            <div class="panel-heading">
                <strong>Dados do Usuário</strong>
            </div>
            <div class="panel-body">

                @using Projeto.Entidades
                @{
                    //resgatar o usuario da sessão..
                    Usuario u = Session["usuario"] as Usuario;
                }

                Login: <strong>@u.Login</strong>
                <br />
            </div>
            <dov class="panel-footer">
                <a href="/Home/Logout" class="btn btn-danger">
                    Sair
                </a>
            </dov>

        </div>
    </div>
</div>
<br />
<br />
<br />


<a href="/TARCTT/CadastroTAR" class="btn btn-primary">Cadastrar Tarefa</a>

<a href="/TARCTT/CadastroCTT" class="btn btn-primary">Cadastrar Contato</a>
<br />
<br />



<table class="table table-bordered">
    <thead>
        <tr>
            <th>Código</th>
            <th>Nome da Tarefa</th>
            <th>Data de Entrega</th>
            <th>Descrição</th>
            <th>Operações</th>
        </tr>
    </thead>
    <tbody>


        @foreach (var item in Model)
        {
            <tr>
                <td> @item.ConsultaTarefaModel.IdTarefa </td>
                <td> @item.ConsultaTarefaModel.Nome </td>
                <td> @item.ConsultaTarefaModel.DataEntrega</td>
                <td> @item.ConsultaTarefaModel.Descricao</td>

                <td>
                    <a href="/Tarefa/Edicao" class="btn btn-primary btn-sm">
                        Atualizar
                    </a>
                    <a href="/Tarefa/Exclusao" class="btn btn-danger btn-sm">
                        Excluir
                    </a>
                </td>
            </tr>

        }


    </tbody>
    <tfoot>
        <tr>
            <td colspan="5">Quantidade de registros: @Model.Count </td>
        </tr>
    </tfoot>
</table>
<br />
<br />
<br />

<table class="table table-bordered">
    <thead>
        <tr>
            <th>Código</th>
            <th>Nome do Contato</th>
            <th>Email</th>
            <th>Telefone</th>
            <th>Operações</th>
        </tr>
    </thead>
    <tbody>


        @foreach (var item in Model)
        {
            <tr>
                <td> @item.ConsultaContatoModel.IdContato </td>
                <td> @item.ConsultaContatoModel.Nome </td>
                <td> @item.ConsultaContatoModel.Email</td>
                <td> @item.ConsultaContatoModel.Telefone</td>

                <td>
                    <a href="/Tarefa/Edicao" class="btn btn-primary btn-sm">
                        Atualizar
                    </a>
                    <a href="/Tarefa/Exclusao" class="btn btn-danger btn-sm">
                        Excluir
                    </a>
                </td>
            </tr>

        }


    </tbody>
    <tfoot>
        <tr>
            <td colspan="5">Quantidade de registros: @Model.Count </td>
        </tr>
    </tfoot>
</table>
  • Include your view

  • On the line "Return View();" right? Only, I have two views to return, which is the CTT list and the TAR list.

  • Put your Materlayoutmodel, there’s something strange in its structure.

  • Good morning! First of all thanks for the layout, I will post along, as is my index.cshtml.

  • I’ll test your suggestions now.

1 answer

0

You can solve several ways, but I recommend you change your view models a little. I will leave an example and edit the answer after you post your Masterlayoutmodel, with the ideal solution.

Edit your Masterlayoutmodel containing the two lists:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Projeto.WEB.Models;

namespace Projeto.WEB.Models
{
    public class MasterLayoutModel
    {
        public IEnumerable<ConsultaTarefaModel> ConsultaTarefaModel { get; set; }
        public IEnumerable<ConsultaContatoModel> ConsultaContatoModel { get; set; }

        //Adicione um construtor para inicialização e evitar null reference
        public MasterLayoutModel()
        {
            ConsultaTarefaModel = new List<ConsultaTarefaModel>();
            ConsultaContatoModel = new List<ConsultaContatoModel>();
        }

    }
}

Populate these lists and send Viewmodel to your View:

namespace Projeto.WEB.Controllers
{
    public class LoggedController : Controller
    {
    // GET: Logged
        [Authorize]
        public ActionResult Index()
        {
            //Instancie e inicialize sua view model apenas uma vez
            var masterLayoutModel = new MasterLayoutModel();

            //Essa lista é desnecessária
            //List<MasterLayoutModel> listaTAR = new List<MasterLayoutModel>();
            try
            {

                TarefaRepositorio rep = new TarefaRepositorio();
                foreach (Tarefa t in rep.FindAll())
                {
                    //MasterLayoutModel mModel = new MasterLayoutModel();
                    ConsultaTarefaModel model = new ConsultaTarefaModel();      
                    UsuarioRepositorio repUsuario = new UsuarioRepositorio();


                    t.Usuario = new Usuario();
                    t.Usuario = repUsuario.FindByLogin(User.Identity.Name);


                    model.IdTarefa = t.IdTarefa;
                    model.Nome = t.Nome;
                    model.DataEntrega = t.DataEntrega;
                    model.Descricao = t.Descricao;

                    //Aqui você estava adicionando um objeto vazio
                    //mModel.ConsultaTarefaModel = new ConsultaTarefaModel();            
                    //listaTAR.Add(mModel); //adicionar na lista..

                    masterLayoutModel.ConsultaTarefaModel(model);
                }

            }
            catch (Exception e)
            {
                //gerar mensagem de erro..
                ViewBag.Mensagem = e.Message;
            }        

            //Essa lista tambem é desnecessária
            //List<MasterLayoutModel> listaCTT = new List<MasterLayoutModel>();
            try
            {

                ContatoRepositorio rep = new ContatoRepositorio();
                foreach (Contato c in rep.FindAll())
                {

                    ConsultaContatoModel model = new ConsultaContatoModel();
                    //MasterLayoutModel mModel = new MasterLayoutModel();
                    UsuarioRepositorio repUsuario = new UsuarioRepositorio();



                    c.Usuario = new Usuario();
                    c.Usuario = repUsuario.FindByLogin(User.Identity.Name);


                    model.IdContato = c.IdContato;
                    model.Nome = c.Nome;
                    model.Email = c.Email;
                    model.Telefone = c.Telefone;

                    //Aqui você estava adicionando um objeto vazio
                    //mModel.ConsultaContatoModel = new ConsultaContatoModel();
                    //listaCTT.Add(mModel);

                    masterLayoutModel.ConsultaContatoModel.Add(model);
                }            

            }
            catch (Exception e)
            {
                //gerar mensagem de erro..
                ViewBag.Mensagem = e.Message;
            }

            //Enviando a model para a view;
            return View(masterLayoutModel);
        }
    }
}

Now edit your View to reflect the new Viewmodel structure in your iterations.

@foreach (var item in Model.ConsultaContatoModel)
{
    <tr>
        <td> @item.IdContato </td>
        <td> @item.Nome </td>
        <td> @item.Email</td>
        <td> @item.Telefone</td>

        <td>
            <a href="/Tarefa/Edicao" class="btn btn-primary btn-sm">
                Atualizar
            </a>
            <a href="/Tarefa/Exclusao" class="btn btn-danger btn-sm">
                Excluir
            </a>
        </td>
    </tr>
}
  • @Luizaylton, you have evolved?

Browser other questions tagged

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