Foreach within a cshtml(view) from a controller

Asked

Viewed 4,814 times

0

I made a code using Linq and jQuery. Turns out you’re giving me a problem I can’t solve, which is creating a Treeview dynamically. Then I had another idea. To do the foreach right in the View (cshtml). Here comes the question, how do I make a foreach within the View and on top of a result of a Linq which is in my controller?

Controller:

[HttpPost]
public JsonResult ArvoreAcao(string _uf)
{
    RupturaEntities db = new RupturaEntities();
    var monta_arvore = (from rup in db.Ruptura
      from apr in db.Apresentacao
          .Where(apr => apr.Codigo_Apresentacao == rup.Codigo_Apresentacao)
      from pdv in db.PDV.Where(pdv => pdv.CodigoPDV == rup.CodigoPDV)
      from mot in db.Motivo.Where(mot => mot.IDMotivo == rup.IDMotivo)
          select new {
              rup.IDRuptura,
              rup.DataRuptura,
              rup.IDMotivo,
              mot.Motivo1,
              rup.IDOrigem,
              rup.CodigoPDV,
              pdv.UF,
              pdv.Cidade,
              loja = pdv.Cnpj + " - " + pdv.Descricao,
              rup.Codigo_Apresentacao,
              apr.Unidade_Negocio,
              apr.Franquia,
              apr.Familia,
              apr.Descricao
          }).ToList().Distinct().OrderBy(apr => apr.Descricao);

    return Json(new { monta_arvore }, JsonRequestBehavior.AllowGet);
}

And that would be the View where the foreach will happen. The foreach would be inside the div jqxTree, ie, would erase all static content from there (fake) and make it dynamically.

@{
    ViewBag.Title = "Acao";
    Layout = "~/Views/Shared/_LayoutBase.cshtml";
}

<link href="~/Content/Jqwidgets/jqx.base.css" rel="stylesheet" type="text/css" />

<h2>Tomada de Ação</h2>

<div class="row">
    <div class="col-md-12">
        <div class="col-md-1">
            <label for="cbxCodTipo">UF:</label>
        </div>
        <div class="col-md-4">
            <select class="form-control col-md-6" name="cbxCodTipo" id="cbxCodTipo" 
                onchange=" return MontaCidades();">
                <option value="00">Selecione um estado</option>
                <option value="AC">ACRE</option>
                <option value="AL">ALAGOAS</option>
                <option value="AP">AMAPÁ</option>
                <option value="AM">AMAZONAS</option>
                <option value="BA">BAHIA</option>
                <option value="CE">CEARÁ</option>
                <option value="DF">DISTRITO FEDERAL</option>
                <option value="ES">ESPÍRITO SANTO</option>
                <option value="GO">GOIÁS</option>
                <option value="MA">MARANHÃO</option>
                <option value="MT">MATO GROSSO</option>
                <option value="MS">MATO GROSSO DO SUL</option>
                <option value="MG">MINAS GERAIS</option>
                <option value="PA">PARÁ</option>
                <option value="PB">PARAÍBA</option>
                <option value="PR">PARANÁ</option>
                <option value="PE">PERNAMBUCO</option>
                <option value="PI">PIAUÍ</option>
                <option value="RJ">RIO DE JANEIRO</option>
                <option value="RN">RIO GRANDE DO NORTE</option>
                <option value="RS">RIO GRANDE DO SUL</option>
                <option value="RO">RONDÔNIA</option>
                <option value="RR">RORAIMA</option>
                <option value="SC">SANTA CATARINA</option>
                <option value="SP">SÃO PAULO</option>
                <option value="SE">SERGIPE</option>
                <option value="TO">TOCANTINS</option>
            </select>
        </div>
        <div class="col-md-6">
            <div class="col-md-2">
                <label for="cbxCidade">Cidade:</label>
            </div>
            <select class="form-control col-md-4" name="cbxCidade" id="cbxCidade">
            </select>
        </div>
    </div>

    <div class="col-md-12">
        <div class="col-md-1">
            <label for="cbxRede">Rede:</label>
        </div>
        <div class="col-md-4">
            <select class="form-control col-md-6" name="cbxRede" id="cbxRede"></select>
        </div>
        <div class="col-md-6">
            <div class="col-md-2">
                <label for="cbxRede">Descrição:</label>
            </div>
            <select class="form-control col-md-4" name="cbxDescricao" id="cbxDescricao">
            </select>
        </div>
    </div>

    <div class="col-md-12">
        <div class="col-md-1">
            <label for="cbxProduto">Produto:</label>
        </div>
        <div class="col-md-4">
            <select class="form-control col-md-6" name="cbxProduto" id="cbxProduto">
            </select>
        </div>
    </div>

    <div class="col-md-12">
        <div class="col-md-1">
            <label for="cbxUnNegocio">Unidade Negócio:</label>
        </div>
        <div class="col-md-4">
            <select class="form-control col-md-6" name="cbxUnNegocio" id="cbxUnNegocio">
            </select>
        </div>
    </div>
</div>

<br />

<div id="content">
    <div class="listTree"></div>
    <button class="btn btn-primary" onclick=" return MontaArvore();">Pesquisar</button>
</div>

<br>

<div id='jqxWidget'>
    <div style='float: left; width:auto;'>
        <div id='jqxTree' style='visibility: hidden; float: left; margin-left: 20px;'>
            <ul>
                <li item-checked='false' item-expanded='false'>
                    Produto
                    <ul>
                        <li item-expanded='true'>
                            MIP
                            <ul>
                                <li item-expanded='true'>
                                    Família: ACCUVIT
                                    <ul>
                                        <li>ACCUVIT COMREV FRX30</li>
                                    </ul>
                                </li>
                                <li item-expanded='true'>
                                    Família: FLOGORAL
                                    <ul>
                                        <li>FLOGORAL SPRAY CEREJA CTX30ML</li>
                                        <li>FLOGORAL SPRAY MENTA CTX30ML</li>
                                        <li>FLOGORAL CREM DENTAL CTX70G</li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>

        <div style='margin-left: 60px; float: left;'>
            <div style='margin-top: 10px;'>
                <input id='jqxCheckBox' type="hidden">
            </div>
        </div>

    </div>
</div>@*Fim da div jqxWidget *@

<div class="row">
    <div class="col-md-12">
        <div class="col-md-2">
            <label for="txtObs">Observação:</label>
        </div>
        <div class="col-md-12">
            <textarea id="txtObs" style="width: 450px;"></textarea>
        </div>
    </div>
</div>

<br />

<div id="content">
    <div class="listTree"></div>
    <button class="btn btn-success" ">Gravar</button>
    @Html.ActionLink("Voltar", "Index", "Home", new {}, new {@class = "btn btn-danger"})
</div>

@*<script class="cssdeck" 
    src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>*@
<script class="cssdeck" 
    src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js">
</script>    
<script src="~/Scripts/Acao/Acao.js"></script>
<script src="~/Scripts/Jqwidgets/jqxcore.js"></script>
<script src="~/Scripts/Jqwidgets/jqxbuttons.js"></script>
<script src="~/Scripts/Jqwidgets/jqxscrollbar.js"></script>
<script src="~/Scripts/Jqwidgets/jqxpanel.js"></script>
<script src="~/Scripts/Jqwidgets/jqxtree.js"></script>
<script src="~/Scripts/Jqwidgets/jqxcheckbox.js"></script>

Important: The controller Is Called AcaoController. The .edmx is inside Model (Folder) and use Entity.

I did it on the controller:

ViewBag.result_arvore = monta_arvore;

And then that in View.

@foreach (var item in ViewBag.result_arvore)
{
    <ul>
        <li item-checked='false' item-expanded='false'>
            @item.Motivo1
        </li>
    </ul>
}

The result is this:

mensagem de erro

How do I make a foreach, but on top of a result from a controller?

I’ve made changes and it gives me the error that I can’t do the foreach, because my class does not have a Getenumerator public property. As I do?

It’s like this now:
My View just the part of foreach. The rest are the same above.

<div id='jqxWidget'>
    <div style='float: left; width:auto;'>
        <div id='jqxTree' style='visibility: hidden; float: left; margin-left: 20px;'>
            @foreach (var item in Model)
            {
                <ul>
                    <li item-checked='false' item-expanded='false'>
                        @item.Motivo
                    </li>
                </ul>
            }
        </div>

        <div style='margin-left: 60px; float: left;'>
            <div style='margin-top: 10px;'>
                <input id='jqxCheckBox' type="hidden">
            </div>
        </div>

    </div>
</div>

The code in my controller:

public ActionResult Acao()
{
    RupturaEntities db = new RupturaEntities();

    var monta_arvore =   db.Ruptura.Select(rup=> new MontaArvoreAcao {
        IDRuptura = rup.IDRuptura,
        DataRuptura = rup.DataRuptura,
        IDMotivo = rup.IDMotivo,
        Motivo = rup.Motivo.Motivo1,
        IDOrigem = rup.IDOrigem,
        CodigoPDV = rup.CodigoPDV,
        UF  = rup.PDV.UF,
        Cidade = rup.PDV.Cidade,
        CnpjDescricao= rup.PDV.Cnpj + " - " + rup.PDV.Descricao,
        Codigo_Apresentacao = rup.Codigo_Apresentacao,
        Unidade_Negocio = rup.Apresentacao.Unidade_Negocio,
        Franquia = rup.Apresentacao.Franquia,
        Familia  = rup.Apresentacao.Familia,
        Descricao = rup.Apresentacao.Descricao
    }).ToList();

    return View(monta_arvore);
}

My Model:

public class MontaArvoreAcao
{
    public int IDRuptura { get; set; }
    public DateTime DataRuptura { get; set; }
    public int IDMotivo { get; set; }
    public string Motivo { get; set; }
    public int IDOrigem { get; set; }
    public string CodigoPDV { get; set; }
    public string UF { get; set; }
    public string Cidade { get; set; }
    public string CnpjDescricao { get; set; }
    public string Codigo_Apresentacao { get; set; }
    public string Unidade_Negocio { get; set; }
    public string Franquia { get; set; }
    public string Familia { get; set; }
    public string Descricao { get; set; }
}

public class MontaArvoreAcaoDBContext : DbContext
{
    public DbSet<MontaArvoreAcao> montaArvoreAcao { get; set; }
}

2 answers

1


Just by reinforcing, you can pass the object in two ways to the view

public ActionResult minhaAcao
{
    List<ObjetoModel> objeto = (from u in objetos select u).toList();
    return View(objeto);
}

Your View would look this way

@model IENumerable<ObjetoModel>

@foreach(var objeto in Model)
{
   @objeto.propriedade <br />
}

And the other way is by using ViewBag that you know how to use.

The Error that is giving your problem is that most likely the query is returning null. Still I advise the use of the return of Json as follows.

Return Json(monta_arvore);

I use this way in my projects for consultations in Json and have always succeeded.

And in your query change to this format.

var monta_arvore = (from rup in db.Ruptura
    from apr in db.Apresentacao.Where(apr => apr.Codigo_Apresentacao == rup.Codigo_Apresentacao)
    from pdv in db.PDV.Where(pdv => pdv.CodigoPDV == rup.CodigoPDV)
    from mot in db.Motivo.Where(mot => mot.IDMotivo == rup.IDMotivo)
        select new {
            rup.IDRuptura,
            rup.DataRuptura,
            rup.IDMotivo,
            mot.Motivo1,
            rup.IDOrigem,
            rup.CodigoPDV,
            pdv.UF,
            pdv.Cidade,
            loja = pdv.Cnpj + " - " + pdv.Descricao,
            rup.Codigo_Apresentacao,
            apr.Unidade_Negocio,
            apr.Franquia,
            apr.Familia,
            apr.Descricao
        }).Distinct().OrderBy(apr => apr.Descricao).ToList();

In his Foreach try to do it this way

<ul>
@foreach (var item in Model)
{
   <li item-checked='false' item-expanded='false'>@item.Motivo</li>
}
</ul>
  • @pnet Need to be sure of one thing, is your query returning result? If yes check in the browser console if you are returning JSON and possible errors in Jquery. Also put your Jquery code here to analyze.

  • Do the Foreach as follows as it is in the edited answer. @pnet some things are leaving me somewhat doubtful, in your div #jqxTree there is a style set for visibility:hidden this will make your div does not appear, if possible put a breakpoint in your query and check if it is returning all records, most likely it is populating the list with an object. Which widget you are using?

  • No, that’s not the problem. There’s a javascript that treats that. If I remove this, it gives a chipped Zica. As you put it, it worked, no problem, Joe. Now yes, I’m going to ride the other kids. Motive is the father and now I have to do with Família, Unidade_negocio and the product itself, which is the tri-grandson of the tree. As your example, for each iteration, there will be a <ul> out, right?

  • Yes, I believe there will be others foreach within each li obviously with a if (checking if the father is his father) and so on.

0

Probably the content of your Viewbag is coming null, will need to do a check before.

You also need to tell your Viewbag type to perform the iteration and access the object properties.

@foreach (var item in (List<SeuTipo>)ViewBag.result_arvore)
{
      <ul>
         <li item-checked='false' item-expanded='false'>
            @item.Motivo1
         </li>
      </ul>
}

Browser other questions tagged

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