View select ASP.NET SqlServer

0

I'm giving maintenance to a controller and I'm getting the data from my database and trying to display it in the view, but I can not pass the select to the view, can anyone help me? select in a table or in normal text.

Here is the code for my controller:

        public ActionResult GetContacts()
    {
        SqlConnection conexao = new SqlConnection(@"Data Source="nomebd";Initial Catalog="nometabela";User ID="usuario";Password="senha"");
        conexao.Open();
        string strQuerySelect = "SELECT * FROM people where id > 0 and id < 100";

        SqlCommand cmdComandoSelect = new SqlCommand(strQuerySelect, conexao);
        SqlDataReader dados = cmdComandoSelect.ExecuteReader();

        var contacts = new List<OrderViewModel>();
        while (dados.Read())
        {
            contacts.Add(new OrderViewModel
            {
                id = dados["id"].ToString(),
                idPessoa = Math.Round(Convert.ToDouble(dados["idPessoa"]) * 3.2, 2),
                Nome = dados["nome"].ToString(),
            });
        }

        return Json(contacts);
    }
    
asked by anonymous 12.06.2018 / 20:32

1 answer

0

With your Typed View you can in your Action give a return View(contacts); and then in your View:

@model OrderViewModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div>
   Conteúdo da View
</div>

Your Action changed:

  public ActionResult GetContacts()
    {
        SqlConnection conexao = new SqlConnection(@"Data Source="nomebd";Initial Catalog="nometabela";User ID="usuario";Password="senha"");
        conexao.Open();
        string strQuerySelect = "SELECT * FROM people where id > 0 and id < 100";

        SqlCommand cmdComandoSelect = new SqlCommand(strQuerySelect, conexao);
        SqlDataReader dados = cmdComandoSelect.ExecuteReader();

        var contacts = new List<OrderViewModel>();
        while (dados.Read())
        {
            contacts.Add(new OrderViewModel
            {
                id = dados["id"].ToString(),
                idPessoa = Math.Round(Convert.ToDouble(dados["idPessoa"]) * 3.2, 2),
                Nome = dados["nome"].ToString(),
            });
        }

        return View(contacts);
    }

Note: "When you give return Json(...) you are specifically telling MVC not to use a view and to serve serialized JSON data" Source: link

    
13.06.2018 / 15:39