I'm trying to use a SQL query in SqlCommand and I'd like to see the complete result set that is returned from SQL Server database, and return Json format after that.
So here is the code in controller:
public ActionResult GetAllSummary()
{
string connectionString ="Data Source=...;Initial Catalog=...;Integrated Security=True";
string query = "SELECT v.date, v.name, v.numbers FROM view as v GROUP BY v.date,v.mane,v.numbers ORDER BY v.date,v.mane,v.numbers";
using(SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, conn);
try {
conn.Open();
SqlDataReader reader = command.ExecuteReader();
// In this part below, I want the SqlDataReader to
// read all of the records from database returned,
// and I want the result to be returned as Array or
// Json type, but I don't know how to write this part.
while(reader.Read())
{
ArrayList result = new ArrayList();
foreach(int i in reader)
// this line below was the code I wrote before.
// But since my query returns multiple
// types (datetime, string, decimal, etc..),
// I don't know what C# command I can use to return
// the results in foreach loop. Or say I even don't
// need a for/foreach loop.
result.Add(reader.GetValue(i));
return Json(result, JsonRequestBehavior.AllowGet);
}
reader.Close();
}
catch(Exception ex)
{
var error = ex.Message;
return View(error);
}
}
return View();
}
Anyone can help me to make this work? I will be greatly appreciated.
Kevin
return Json(...inside theforeachloop so it immediately exits the method and returns a result as soon as the first value of first row is read.Date,NameandNumbersand inside thewhileloop, initialize an instance of your model, set its properties and add it to a collection and finally return a collection of your model. Step 3. Call the service in your controller to getList<yourModel>and then return it to the view.