How do I call two models in one view?

Asked

Viewed 115 times

0

Good morning people, I’m new to Asp so my knowledge is very low, could you help me with this question? I have a query view that already has a "BOOK" model, and in this same view I intend to leave a dropdown for login, but for this I need the "USERS" model to arrive in this view, could you please give me an example, so I can understand? follows codes:

inserir a descrição da imagem aqui

CSHTML:

@model IEnumerable<Repasse.Models.LIVRO>
<!DOCTYPE html>
<html lang="pt-br" dir="ltr">
<head>
    <title>Repasse - Cadastros de Alunos</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="icon" type="image/x-icon" href="~/img/icone.png" />
    <link rel="stylesheet" type="text/css" href="~/content/webfonts/all.min.css">
    <link rel="stylesheet" type="text/css" href="~/content/webfonts/fontawesome.min.css">
    <link rel="stylesheet" type="text/css" href="~/content/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="~/content/css/livro/consultalivrohome.css" />
</head>
<body>
    <!--SEÇÃO DO CABEÇALHO-->
    <header>
        <!-- 001 - NOmE E ICONE DO PROJETO NO NAVBAR -->
        <nav class="navbar fixed-top navbar-expand-lg navbar-dark" style="background-color: #033157;">
            <a class="navbar-brand" style="color: #b5b5b5;"><span class="fas fa-books" style="color: #b5b5b5;"></span> Repasse</a>
            <!-- 001 - FIM -->
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="@Url.Action("Index", "Home")">Início</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="@Url.Action("Consultar", "Home")">Consultar Livros</a>
                    </li>
                </ul>
                <ul class="nav navbar-nav navbar-right ml-auto">
                    <li class="nav-item dropdown">
                        <a data-toggle="dropdown" class="nav-link dropdown-toggle" href="#"><i class="fa fa-user-o"></i> Entrar</a>
                        <ul class="dropdown-menu">
                            <li>
                                <form class="form-inline login-form" method="post">
                                    @Html.AntiForgeryToken()
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="fas fa-user-circle"></i></span>
                                        @Html.TextBoxFor(m => m.USUARIO, new { id = "first-name", @class = "form-control", type = "text", name = "username", placeholder = "Usuário" })
                                        @Html.ValidationMessageFor(m => m.USUARIO, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="fas fa-lock"></i></span>
                                        @Html.PasswordFor(m => m.SENHA, new { @class = "form-control", type = "password", name = "pass", placeholder = "Senha" })
                                        @Html.ValidationMessageFor(m => m.SENHA, "", new { @class = "text-danger" })
                                    </div>
                                    <button type="submit" class="btn btn-primary">Entrar</button>
                                </form>
                            </li>
                            @*@{ if (ViewBag.Erro != null)
                                    {
                                        <div class="alert alert-danger alert-dismissible fade show btn-block" role="alert">
                                            <h6 style="color:red">@ViewBag.erro</h6>
                                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                <span aria-hidden="true">&times;</span>
                                            </button>
                                        </div>
                                    }
                                }*@
                        </ul>
                    </li>
                </ul>
            </div>
        </nav>
    </header>
    <!--SEÇÃO DO CORPO-->
    <section class="corpo">
        <div class="buscartitulo">
            <section id="buscaraluno" class="search-sec">
                <h4 class="text-center mt-4"><i class="fas fa-print-search"></i> CONSULTAR LIVRO</h4>
            </section>
        </div>
        <div class="container">
            <div class="table-wrapper">
                <div class="tabela-container">
                    <table id="datatable" class="table table-striped table-bordered" style="width:100%">
                        <thead>
                            <tr>
                                <th>COD.LIVRO</th>
                                <th>NUM.TOMBO</th>
                                <th>COD.ISBN</th>
                                <th>TITULO</th>
                                <th>ANO</th>
                                <th>EDIÇÃO</th>
                                <th>EDITORA</th>
                                <th>SITUAÇÃO</th>
                                <th>CATEGORIA.LIVRO</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var item in Model)
                            {
                                <tr>
                                    <td>@Html.DisplayFor(modelItem => item.COD_LIVRO)</td>
                                    <td>@Html.DisplayFor(modelItem => item.NUM_TOMBO)</td>
                                    <td>@Html.DisplayFor(modelItem => item.COD_ISBN)</td>
                                    <td>@Html.DisplayFor(modelItem => item.TITULO)</td>
                                    <td>@Html.DisplayFor(modelItem => item.ANO)</td>
                                    <td>@Html.DisplayFor(modelItem => item.EDICAO)</td>
                                    <td>@Html.DisplayFor(modelItem => item.SITUACAO)</td>
                                    <td>@Html.DisplayFor(modelItem => item.CATEGORIA_LIVRO)</td>
                                    <td>@Html.DisplayFor(modelItem => item.EDITORA)</td>

                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
    <!--SEÇÃO DO RODAPÉ-->
    <footer>
        <nav id="rodape" class="navbar sticky-top">
            <a class="navbar-brand">
                <p class="textorodape">Copyright &copy; Hello Word - Repasse | ITB - Instituto Técnico de Barueri - Brasílio Flores de Azevedo</p>
            </a>
        </nav>
    </footer>

    <!--SEÇÃO DO JAVASCRIPT-->
    <script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="~/Scripts/dataTables.bootstrap4.min.js"></script>
    <script type="text/javascript" src="~/Scripts/bootstrap.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#datatable').DataTable({
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.10.19/i18n/Portuguese-Brasil.json"
                }
            });
        });
    </script>
</body>
</html>

Controller:

using Repasse.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace Repasse.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(USUARIOS log)
        {
            if (ModelState.IsValid)
            {
                using (var db = new DBREPASSEEntities())
                {
                    var v = db.USUARIOS.Where(a => a.USUARIO.Equals(log.USUARIO) && a.SENHA.Equals(log.SENHA)).FirstOrDefault();
                    if (v != null)
                    {

                        Session["nomeUsuarioLogado"] = v.NOME_USUARIO.ToString();
                        Session["telefoneUsuarioLogado"] = v.FONE_USUARIO.ToString();
                        Session["cpfUsuarioLogado"] = v.CPF_USUARIO.ToString();
                        Session["emailUsuarioLogado"] = v.EMAIL_USUARIO.ToString();
                        return RedirectToAction("Inicio", "Bibliotecario");
                    }
                    else ViewBag.Erro = "Campo senha ou usuário inválido!";
                }
            }
            return View();

        }

        public ActionResult Consultar()
        {
            DBREPASSEEntities db = new DBREPASSEEntities(); // Aqui coloca sua conexão com o banco de dados
            List<LIVRO> listaaluno = db.LIVRO.Where(x => x.STATUS_DEL == "I").OrderBy(x => x.TITULO).ToList<LIVRO>();

            return View(listaaluno);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Consultar(USUARIOS log)
        {
            if (ModelState.IsValid)
            {
                using (var db = new DBREPASSEEntities())
                {
                    var v = db.USUARIOS.Where(a => a.USUARIO.Equals(log.USUARIO) && a.SENHA.Equals(log.SENHA)).FirstOrDefault();
                    if (v != null)
                    {

                        Session["nomeUsuarioLogado"] = v.NOME_USUARIO.ToString();
                        Session["telefoneUsuarioLogado"] = v.FONE_USUARIO.ToString();
                        Session["cpfUsuarioLogado"] = v.CPF_USUARIO.ToString();
                        Session["emailUsuarioLogado"] = v.EMAIL_USUARIO.ToString();
                        return RedirectToAction("Inicio", "Bibliotecario");
                    }
                    else ViewBag.Erro = "Campo senha ou usuário inválido!";


                }

            }
            return View();

        }

        public ActionResult Login()
        {
            return View();
        }

    }
}

MODEL USERS:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Repasse.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class USUARIOS
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public USUARIOS()
        {
            this.EMPRESTIMO = new HashSet<EMPRESTIMO>();
        }
    
        public int COD_USUARIO { get; set; }
        public string NOME_USUARIO { get; set; }
        public string FONE_USUARIO { get; set; }
        public string EMAIL_USUARIO { get; set; }
        public string SEXO_USUARIO { get; set; }
        public string CPF_USUARIO { get; set; }
        public string USUARIO { get; set; }
        public string PERFIL { get; set; }
        public string SENHA { get; set; }
        public string CONFIRMARSENHA { get; set; }
        public string STATUS_DEL { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<EMPRESTIMO> EMPRESTIMO { get; set; }
    }
}

MODEL BOOK:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Repasse.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class LIVRO
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public LIVRO()
        {
            this.AUTORIA = new HashSet<AUTORIA>();
            this.AUTORIA1 = new HashSet<AUTORIA>();
            this.ITENS_EMPRESTIMO = new HashSet<ITENS_EMPRESTIMO>();
        }
    
        public int COD_LIVRO { get; set; }
        public Nullable<int> NUM_TOMBO { get; set; }
        public string COD_ISBN { get; set; }
        public string TITULO { get; set; }
        public Nullable<System.DateTime> ANO { get; set; }
        public string EDICAO { get; set; }
        public string SITUACAO { get; set; }
        public Nullable<int> COD_CATEG { get; set; }
        public Nullable<int> COD_EDITORA { get; set; }
        public string STATUS_DEL { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AUTORIA> AUTORIA { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AUTORIA> AUTORIA1 { get; set; }
        public virtual CATEGORIA_LIVRO CATEGORIA_LIVRO { get; set; }
        public virtual EDITORA EDITORA { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ITENS_EMPRESTIMO> ITENS_EMPRESTIMO { get; set; }
    }
}

  • check if this post helps you: https://answall.com/questions/400746/comor-propriedades-de-other_model/400773#400773

  • Dude, I gave you a point on the negative question, now I’m gonna answer you...

2 answers

1

You said you have a view to consult books and you have a "BOOK" model. This means that your "model" book relates to your database, BOOK should also be your table. So your model is your database table.

It turns out that in MVC, people usually send the "model" (data structure) directly to view. Some have the view that the model is the database itself.

However, your requirement is that your view gather information from different models. BOOK AND USER. So maybe the model your VIEW needs should be a DTO (data transfer Object). That is, an object, which has the presentation data structure, which will meet the data visualization needs of your VIEW and which will aggregate values of different structures of the databases.

I mean, your DTO should be something like:

public class HomeItemDTO
{
  public string CodigoLivro {get; set;}
  public string NumeroTumbo {get; set;}
  public string CodigoISBN {get; set;}
  public string Titulo {get; set;}
  public string Ano {get; set;}
  public string Edicao {get; set;}
  public string Editor {get; set;}
  public string Situação {get; set;}
  public string CategoriaLivro {get; set;}
}

Ai you can create an SQL that joins the two tables and already populates different information in this DTO or you can transmute the results of the repositories of Users and Books in this DTO object.

1

You can pass the model by ViewData[""], for example.

But the way you have this application you’re not using the full potential of the . NET MVC architecture.

You should create a Layout which traverses all pages in the application in a single file, example, and use the RenderBody() to present the various pages (list of users, list of books, creation users, etc.).

You should also isolate that section of login on PartialView that would make your doubt nonexistent.

If you create a project from scratch with Visual Studio you will have all this already done and I advise you to study and try a little.

Browser other questions tagged

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