View select ASP.NET Sqlserver

Asked

Viewed 52 times

0

I’m maintaining 1 controller and I’m taking the data from my database and trying to display it in the view, however I can’t pass select to the view, can anyone help me? i need to pass all select data in a table or in normal text.

Follow the code of 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);
    }
  • Marcelo, are you getting back into Contracts? puts a break point and hovers over, see if there are items inside it... If yes I can help you.

1 answer

0

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

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

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

Its amended Action:

  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 a return Json(...) is specifically telling MVC not to use a view and to serve serialized JSON data" Source: https://stackoverflow.com/a/15197674/4312593

Browser other questions tagged

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