I am trying to read values form my database. But why am I getting only values with no column name? this is my controller. that returns the values in JSON

            SqlCommand cmd = con.CreateCommand();

            cmd.CommandText = "SELECT DISTINCT State FROM MyDBtable";

            con.Open();
            List<string> StateList = new List<string>();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                StateList.Add(reader[0].ToString());
            }

            return Json(new
            {
                myTable = StateList
            }, JsonRequestBehavior.AllowGet);

and this is my JSON

{"myTable":["VA","CA"]}

Where as, it's suppose to give me

{"myTable":[{"State":"VA"},{"State":"CA"}]}

Why is it not reading and printing State

有帮助吗?

解决方案 2

Because you are selecting state. This will create a new object where the State property is assigned the state, such that you get what you want:

SqlCommand cmd = con.CreateCommand();

cmd.CommandText = "SELECT DISTINCT State FROM MyDBtable";

con.Open();
List<string> StateList = new List<string>();
SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
    StateList.Add(reader[0].ToString());
}

return Json(new
{
    myTable = StateList.Select(i => new { State = i })
}, JsonRequestBehavior.AllowGet);

For additional columns, see lazyberezovsky's answer who has changed StateList to solve this.

其他提示

String does not have property "State". Create anonymous type instead:

myTable = StateList.Select(s => new { State = s })

UPDATE: Easiest solution for multiple columns - create a DTO for that

public class MyItem // of course use more descriptive name
{
   public string State { get; set; }
   public string Capital { get; set; }
   // etc
}

And fill it from reader:

List<MyItem> items = new List<MyItem>();

while (reader.Read())
{
    MyItem item = new MyItem();
    item.State = reader[0].ToString(); 
    item.Capital = reader[1].ToString(); 
    // etc
    items.Add(item);
}

return Json(new {  myTable = items }, JsonRequestBehavior.AllowGet);

One more sample (with Dapper, which you can find on NuGet). Add using Dapper; to your code. Use same DTO class, as above.

using (var connection = new SqlConnection(connectionString))
{
    connection.Open();
    return Json(new {
       myTable = connection.Query<MyItem>("SELECT * FROM MyDBtable").ToList()
    }, JsonRequestBehavior.AllowGet);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top