Multiple data shown from database into the same view

Viewed 30

In my controller i have this:

private void FetchData()
        {
           //Reinicia a varíavel addresses se já conter algo
                if (addresses.Count > 0)
                {

                    addresses.Clear();
                }
                try
                {
                    con.Open();
                    com.Connection = con;
                    com.CommandText = "SELECT [ID], [SYSTEM_NAME], [SYSTEM_STATUS], [SYSTEM_SHORTMSG] FROM [CORE_SYS_STATUS]";
                    dr = com.ExecuteReader();
                    while (dr.Read())
                    {
                    //Lê os dados da base de dados 
                        addresses.Add(new GestaoAlertas()
                        {
                            ID = (int)dr["ID"]
                        ,
                            SYSTEM_NAME = dr["SYSTEM_NAME"].ToString()
                        ,
                            SYSTEM_STATUS = dr["SYSTEM_STATUS"].ToString()
                        ,
                            SYSTEM_SHORTMSG = dr["SYSTEM_SHORTMSG"].ToString()

                        });
                    }
                    con.Close();
                    }
              //Mostra o erro se houver um
                catch (Exception ex)
                {
                   throw ex;
                }
        }

And then i put it in my view:

public IActionResult Index()
        {
            FetchData();
            return View(addresses);
        }

I was wondering how do i put more data (different table) into the Index view, i tried doing a addresses2 but it doesn't make sense because I can't put it on the "return View()".

2 Answers

You can provide an object holding your data. Something like this:

internal class DataContainer {
    Addresses Addresses { get; set; }
    Addresses Addresses2 { get; set; }
}

and use it like this:

return View(new DataContainer { Addresses = addresses, Addresses2 = addresses2 });

Alternatively you could also use (named) tuples, which is maybe easier as you do not have to created types.

Code of the head, not written in an IDE with syntax highlightening or error checks

I think you can push Addresses List to view.

Declare this this list.

List<List<GestaoAlertas>> allAddresses = new List<List<GestaoAlertas>>();

and push your lists to allAdresses.

List<GestaoAlertas> addresses = new List<GestaoAlertas>();
while (dr.Read())
{
  addresses.Add(new GestaoAlertas()
    {
      ID = (int)dr["ID"],
      SYSTEM_NAME = dr["SYSTEM_NAME"].ToString(),
      SYSTEM_STATUS = dr["SYSTEM_STATUS"].ToString(),
      SYSTEM_SHORTMSG = dr["SYSTEM_SHORTMSG"].ToString()
    });
}
allAddresses.Add(addresses);

After than you can pass the allAddresses to your view. (Don't forget you need to change Model to List<List> on your view.)

public IActionResult Index()
    {
        FetchData();
        return View(allAddresses);
    }
Related