Display the return of a query with 2 tables in the same View in ASP.NET MVC

1

Controller:

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

namespace HelloMobile.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        private BANCOTESTEEntities dao = new BANCOTESTEEntities();



        public ActionResult Index()
        {
            try
            {
               var Query =
                from categoria in dao.TB_CATEGORIA
                join subcategoria in dao.TB_SUB_CATEGORIA on categoria.IDCATEGORIA equals subcategoria.IDCATEGORIA 
                select new {idCategoria = categoria.IDCATEGORIA,
                            DesCategoria = categoria.DESCRICAO_CATEGORIA,
                            idSubCategoria = subcategoria.IDSUBCATEGORIA,
                            DesSubCategoria = subcategoria.DESCRICAO_SUBCATEGORIA };

                return View(Query.ToList());
            }
            catch (Exception ex)
            {
                TempData["Erro"] = "Erro na consulta dos dados " + ex.Message;
            }

            return View();
        }





    }
}

I thought about making a generic class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HelloMobile.Models
{
    public class CLTB_CATEGORIA
    {
        public virtual ICollection<TB_CATEGORIA> TB_CATEGORIAS { get; set; }
        public virtual ICollection<TB_SUB_CATEGORIA> TB_SUB_CATEGORIAS { get;set;}
    }
}

View:

@model List<HelloMobile.Models.CLTB_CATEGORIA>

@{
    ViewBag.Title = "Index";
}


       <div data-role="panel" id="categorias" data-position="left" data-display="reveal" data-theme="a">

            <div data-role="controlgroup" class="ui-icon-alt" > 

            @foreach (var categoria in Model)
             { 
                 <div data-role="collapsible" data-mini="true" data-theme="a" data-content-theme="a">
                    <h1>@categoria.DESCRICAO_CATEGORIA</h1>
                    <ul data-role="listview">
                        @foreach (var subcategoria in Model)
                        { 
                          <li><a href="#perguntas" class="ui-btn ui-mini" data-rel="close" data-transition="fade">@subcategoria.</a></li>  
                        }
                    </ul>
                </div>
             }

            </div>
     </div>
    
asked by anonymous 14.07.2015 / 22:22

1 answer

1

In your action result, you can instantiate a CLTB_CATEGORIA , popular the two properties, and send it to View. Usually use:

Your Controller

var modelo = new TB_CATEGORIAS();
modelo.TB_CATEGORIAS = Query.ToList();
return View(modelo);

In View:

@foreach (var categoria in Model.TB_CATEGORIAS)
    
14.07.2015 / 22:33