Doubt with foreach com group by Asp.net mvc

Asked

Viewed 870 times

0

I have an appointment with a group.

 public List<TB_POSSIBILIDADE> ListarTodos(int id)
        {
            var strQuery = "";
            strQuery += " select ";
            strQuery += " a.IDPOSSIBILIDADE,";
            strQuery += " a.IDTITULOPOSS,";
            strQuery += " A.IDMODALIDADE,";
            strQuery += " a.TITULO,";
            strQuery += " a.DESCRICAO01,";
            strQuery += "  a.DESCRICAO02,";
            strQuery += "  a.DESCRICAO03,";
            strQuery += "  a.VALOR01,";
            strQuery += "  a.VALOR02,";
            strQuery += "  a.VALOR03,";
            strQuery += "  a.MARCA1,";
            strQuery += "  a.MARCA2,";
            strQuery += "  a.MARCA3,";
            strQuery += "  a.VALORAPOSTA1,";
            strQuery += "  a.VALORAPOSTA2,";
            strQuery += "  a.VALORAPOSTA3,";
            strQuery += "  a.VALORTOTAL1,";
            strQuery += "  a.VALORTOTALRETORNO";
            strQuery += " from TB_POSSIBILIDADE a";
            strQuery += " inner join TB_TITULO_POSSIBILIDADE b on a.IDTITULOPOSS = b.IDTITULOPOSS";
            strQuery += string.Format(" where A.IDMODALIDADE = {0}  ", id);
            strQuery += "  group by a.IDTITULOPOSS,a.IDPOSSIBILIDADE,";
            strQuery += "  b.DESCRICAO, a.TITULO,";
            strQuery += "   a.DESCRICAO01, a.DESCRICAO02,";
            strQuery += "   a.DESCRICAO03,a.VALOR01,";
            strQuery += "   a.VALOR02,a.VALOR03,";
            strQuery += "   a.MARCA1,a.MARCA2,";
            strQuery += "   a.MARCA3, a.VALORAPOSTA1,";
            strQuery += "  a.VALORAPOSTA2, a.VALORAPOSTA3,";
            strQuery += "  a.VALORTOTAL1,a.VALORTOTALRETORNO,A.IDMODALIDADE";

            using (contexto = new Contexto())
            {
                var retornoDataReader = contexto.ExecutaComandoComRetorno(strQuery);
                return TransformaReaderEmListaObjetos(retornoDataReader);
            }

        }

I have an accordion where in the body in a few moments I will have more than 1 option.

I have the first option with only one line: Initial A title : winner

I have the second option where I have 1 title and 4 more contents initial A title : mode 02

I want to repeat this content within the same accordion

inserir a descrição da imagem aqui

I created a class:

namespace Generico.Dominio
{
   public class TitulosNaLista
    {
        public string Titulo { get; set; }

    }
}

In Controller I made:

//verifcar os titulos na lista
List<TitulosNaLista> ver = new List<TitulosNaLista>();

public bool VerificarTitulos(string Titulo)
{
    return ver.Any(ls => ls.Titulo == Titulo);
}

in the view:

  <div class="list-group">
                          <a href="#" class="list-group-item active">
                              Selecione uma opção:
                          </a>

                          @if (Model.Count() > 0)
                          {

                          foreach (var item in Model)
                          {


                          if(!VerificarTitulos(item.TITULO))
                          {

                          <!--inicio-->
                          <div class="panel-group" id="accordion">

                              <div class="panel panel-default">
                                  <div class="panel-heading">
                                      <h4 class="panel-title">
                                          <a data-toggle="collapse" data-parent="#accordion" href="#@Html.DisplayFor(c => item.IDPOSSIBILIDADE)">
                                              @Html.DisplayFor(c => item.TITULO)
                                          </a>
                                      </h4>
                                  </div>


                                  <!--inicio do corpo-->
                                  <div id="@Html.DisplayFor(c => item.IDPOSSIBILIDADE)" class="panel-collapse collapse">
                                      <div class="panel-body">


                                          <div class="row">


                                              <div class="col-md-3 form-group">
                                                  @Html.DisplayFor(c => item.DESCRICAO01) | R$ @Html.DisplayFor(c => item.VALOR01)
                                                  @Html.TextBoxFor(c => item.VALORAPOSTA1, new { placeholder = "valor ", @class = "form-control" })
                                              </div>


                                              <div class="col-md-3 form-group">
                                                  @Html.DisplayFor(c => item.DESCRICAO02) | R$ @Html.DisplayFor(c => item.VALOR02)
                                                  @Html.TextBoxFor(c => item.VALORAPOSTA2, new { placeholder = "valor ", @class = "form-control" })
                                              </div>


                                              <div class="col-md-3 form-group">
                                                  @Html.DisplayFor(c => item.DESCRICAO03) | R$ @Html.DisplayFor(c => item.VALOR03)
                                                  @Html.TextBoxFor(c => item.VALORAPOSTA3, new { placeholder = "valor ", @class = "form-control" })
                                              </div>


                                          </div>


                                          <div class="modal-footer">
                                              <button class="btn btn-primary" type="submit" name="opcao" value="">Gravar</button>
                                          </div>

                                      </div>
                                  </div>

                                  <!--fim do corpo -->


                              </div>
                              }


                          </div>
                          <!--fim -->
                          }

                          }

                          }

                      </div>

have a mistake; inserir a descrição da imagem aqui

  • Why not change the query by adding one group by?

  • Friend, I suggest you change your question, your problem is in your query and not in foreach !

  • Expose the query that will be easier to help!

  • As I mentioned in my question, the data is in the same table, I don’t have two tables

  • I’ll create another table for the title and post the question

  • @Mauríciojúnior, I made the adjustment, you can give me a help! I appreciate

  • @Marllonnasser, I made the adjustment, I could see now! I thank you

  • The problem is in the query... you need all the information from select? Because apparently you don’t need... You can even solve in the view, but will be a gambiarra at the end.

  • @Marllonnasser, I changed my question, added the code that was suggested by Joy, note that I have a class Titulosnalista and in control I have a Verifititulos, I wanted to see what the best solution to solve this

  • You bring the data by query...the data already come wrong, right? ... you have to handle in query, not in application.

Show 5 more comments

5 answers

4


In his View there is no method VerificarTitulos(), therefore the mistake.

To show only one title (excluding other data, if different), you can do it in two ways.

Group By direct consultation or Group By in his View (that I consider simpler).

To make the Group By in View, just do the following:

foreach (var item in Model.GroupBy(x => x.Titulo).Select(grp => grp.First()).ToList())
{
  <!--inicio-->
  <div class="panel-group" id="accordion">

      <div class="panel panel-default">
          <div class="panel-heading">
              <h4 class="panel-title">
                  <a data-toggle="collapse" data-parent="#accordion" href="#@Html.DisplayFor(c => item.IDPOSSIBILIDADE)">
                      @Html.DisplayFor(c => item.TITULO)
                  </a>
              </h4>
          </div>
          ...

This way you are grouping by title and selecting only the first value. The others will be disregarded.

It is worth noting that depending on the amount of records, the best option would be to do directly in the query.

  • I’ll try, but groupy by already exists, see the sql query at the beginning of the question

  • @itasouza In the answer I am doing group by in the application. To do in SQL I would have to see better the system

  • I’ve already reviewed the problem, thank you

3

I don’t quite understand the doubt, but I think this should help:

 <div>
<label>Utilizadores: </label>
<% 
    string [] F = new string[6];
    F[0] = "Paulo Mendes";
    F[1] = "Pedro Litio";
    F[2] = "Maria  ";
    F[3] = "Ana";
    F[4] = "Ricardo";
    F[5] = "Beto";
    for (int a =0; a <= 5; a++)
    {
        Response.Write("<a href=\"#\">  " + F[a] + "</a>");
    }

 %>
  </div>

it will repeat the link 6 times.

  • friend, I appreciate the help, but I preferred to do it the right way, see if you can help me, I appreciate

  • your problem is he repeats the same information?

  • see, in the image, the accordion title repeats, I want when you have more than 1 option, come inside the same accordion

  • That code you sent is not Razor from ASP.NET MVC.

  • The goal is just to create an idea of how to solve the problem.

2

Por que ocorre esse erro:

The error occurs because the method "Verify securities" that you are using in View does not exist in the context of View.

As the method "Verify securities" was stated in his Controller it is not possible to call you directly as you are doing in your View thus:

if(!VerificarTitulos(item.TITULO)) // Erro, pois o método não existe na View
{
    ...
}

Sugestão de uma das possíveis soluções:

An alternative would be to create a property in your Model that represents a boleano and is used on condition if() in his View.

Example:

Model

public class SeuModel
{
    // Propriedades que já estão no seu Model
    public string TITULO { get; set; }
    public int IDPOSSIBILIDADE { get; set; }
    ...

    // Nova propriedade no seu Model
    public bool NovaPropriedadeBoleana { get; set; }

    // Seguindo o código enviado você instancia sua lista
    // Pelo seu código não vi como, mas imagino que você preenche a lista
    // Então você poderia usar o método para ao invés de retornar um bool
    // ele configurar essa NovaPropriedadeBoleana exemplo:

    List<TitulosNaLista> ver = new List<TitulosNaLista>();

    ... // preenche a lista

    // Configura a propriedade NovaPropriedadeBoleana 
    public void VerificarTitulos()
    {
        NovaPropriedadeBoleana = ver.Any(ls => ls.Titulo == Titulo);
    }
}

View

@model SeuProjeto.Models.SeuModel

    <div class="list-group">
        ...
        @if (Model.Count() > 0)
        {
            foreach (var item in Model)
            {
               if(!item.NovaPropriedadeBooleana) // Ao invés de usar o método você usaria uma propriedade do seu Model
               {
                    ....
               } ...
            } ...
         } ...
    </div>

Another option is to do the Group By according to Randrade’s reply, there in the case would not even need the method that gave error.

  • I’ll try, but groupy by already exists, see the sql query at the beginning of the question

  • Oh yes, as I focused my answer according to the mistake you quoted in the question, only after I saw that beyond the error, you were doubtful in group by also

  • I’ve already reviewed the problem, thank you

1

Friend, you are using MVC with which database? It is a choice not to use Entity Framework, or you do not know?

Frankly, I see several flaws in your development pattern that generate errors!

1) Concatenation of the same string several times!

Solution: The Stringbuilder class is used for this, but I wouldn’t even use stringbuilder, I would use Linq from Entities - Entity Framework

2) Using SQL failed in code and exchanging values with string.format:

Solution: Not used this way because it allows SQL Injection, it uses classes with Sqlparameter

3) You’re imagining that a method created in the Controller is accessible in the View!

Solution: No! in View you can instantiate a new call from any class (putting namespace using at the beginning).

4) Use Entity Framework, it’s simple... there are many examples on the internet!

5) And finally, it would be more readable for us to put an image with what you want (prototype) and its database!

  • 1

    Mauricio, my project has 4 layers, application, domain, repository and web. In the web project I have the reference of dlls, I am following a pattern I learned using pure sql yes, I have already used the Enitity Framework, which in my point of view is not good for various reasons, it may even be easier, maybe you have another concept more this ease of Link for things simple until it is good, more when you need to do something more complex then you have a problem because the Linq and a new way of doing things, and develop for web to have a lot of language involved.

  • See @itasouza at the beginning really the Entity Framework was kind of complicated, today in its version 6 is very stable and dishonorable many things, allowing a considerable optimization in development.

  • I develop using Latin for years, and I advise you to use, we would kill this your problem in seconds! Just to understand, Linq to entities, optimizes in several ways a query to SQL, and for you to be aware of one of the things that pleases me most, it manages to compose in a single query SQL (native) ... a query Master -> Details of several layers...

  • Have you managed to resolve the issue? If you don’t put a prototype of the final result you want with the structure of the tables, that makes it easy to solve!

  • 1

    I can solve using a partial view

1

 //criar uma classe
public class Titulos_ Na_lista
 {
public string Titulo { get; set; }

  }

  // aqui é a tua página

 List<Titulos_ Na_lista> Ver = new List<Titulos_ Na_lista>();

 public bool VERIFICAR_Titulos(int Titulo)
 {
     return Ver.Any(l => l.Titulo ==Titulo);
 }

 foreach (var item in Model)

{
      if (!VERIFICAR_IDs(item.TITULO))
      {
              <div class="panel-group" id="accordion">

                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h4 class="panel-title">
                                <a data-toggle="collapse" data-parent="#accordion" href="#@Html.DisplayFor(c => item.IDPOSSIBILIDADE)">
                                    @Html.DisplayFor(c => item.TITULO)
                                </a>
                            </h4>
                        </div>

                        <!--inicio do corpo-->
                        <div id="@Html.DisplayFor(c => item.IDPOSSIBILIDADE)" class="panel-collapse collapse">
                            <div class="panel-body">


                                <div class="row">


                                    <div class="col-md-3 form-group">
                                        @Html.DisplayFor(c => item.DESCRICAO01) | R$ @Html.DisplayFor(c => item.VALOR01)
                                        @Html.TextBoxFor(c => item.VALORAPOSTA1, new { placeholder = "valor ", @class = "form-control" })
                                    </div>


                                    <div class="col-md-3 form-group">
                                        @Html.DisplayFor(c => item.DESCRICAO02) | R$ @Html.DisplayFor(c => item.VALOR02)
                                        @Html.TextBoxFor(c => item.VALORAPOSTA2, new { placeholder = "valor ", @class = "form-control" })
                                    </div>


                                    <div class="col-md-3 form-group">
                                        @Html.DisplayFor(c => item.DESCRICAO03) | R$ @Html.DisplayFor(c => item.VALOR03)
                                        @Html.TextBoxFor(c => item.VALORAPOSTA3, new { placeholder = "valor ", @class = "form-control" })
                                    </div>


                                </div>


                                <div class="modal-footer">
                                    <button class="btn btn-primary" type="submit" name="opcao" value="">Gravar</button>
                                </div>

                            </div>
                        </div>

                        <!--fim do corpo -->
                    </div>

                </div>
      }
}
  • Joy, it almost worked, I changed the text of my question by doing the steps you are reporting, see what happens, thank you

  • I’ve already reviewed the problem, thank you

Browser other questions tagged

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