First and foremost I Know how to return a Json Query by doing this
public JsonResult streams()
{
using (var conn = new NpgsqlConnection(Connectionstring))
{
conn.Open();
var credentials = conn.Query<Streams>("select id,name from streams").ToList();
ViewData["Message"] = "Your application description page.";
conn.Close();
return Json(credentials);
}
}
That code above returns Json for me from the database, however now I am actually returning the Json from the SQL code by changing the query to this
var credentials = conn.Query<Streams>("select SELECT array_to_json(array_agg(t)) from (select id,name from streams) t").ToList();
That new query works correctly however it is returning null in the Controller as I have it like this now
public JsonResult streams()
{
using (var conn = new NpgsqlConnection(Connectionstring))
{
conn.Open();
var credentials = conn.Query<Streams>("SELECT array_to_json(array_agg(t)) from (select id,name from streams) t").ToList();
ViewData["Message"] = "Your application description page.";
conn.Close();
return Json(credentials);
}
}
How can I fix this ? My assumption is that using JsonResult and returning Json as an action is messing things up because the SQL query is already returning Json.
This is my Stream Class
public class Streams
{
[Key]
public int id { get; set; }
public string name { get; set; }
public int profile_id { get; set; }
public DateTime created_on { get; set; }
public int last_reply { get; set; }
public int comments { get; set; }
public string city { get; set; }
public string state { get; set; }
public float latitudes { get; set; }
public float longitudes { get; set; }
public int votes { get; set; }
}
It's because you have Json in your string and the call to this.Json(object)
is designed to serialize it to Json.
In MVC 5 you could:
return this.Content(credentials, "application/json");
The ContentResult
class is in MVC Core, so I assume that the syntax remains the same.