asp.net mvc核心如何返回Json查询 [英] asp.net mvc core how can I return a Json query

查看:94
本文介绍了asp.net mvc核心如何返回Json查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道如何通过执行此操作来返回Json查询

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);
    }
}

上面的代码从数据库中为我返回了Json,但是现在我实际上是通过将查询更改为SQL来从SQL代码中返回Json

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();

该新查询正常工作,但是由于我现在这样,它在Controller中返回null

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);
    }
}

我该如何解决?我的假设是,使用JsonResult并将Json作为操作返回是搞砸了,因为SQL查询已经返回了Json.

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.

这是我的流课程

  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; }
    }

推荐答案

这是因为您的字符串中包含Json,并且对this.Json(object)的调用旨在将其序列化为Json.

It's because you have Json in your string and the call to this.Json(object) is designed to serialize it to Json.

在MVC 5中,您可以:

In MVC 5 you could:

return this.Content(credentials, "application/json");

ContentResult 类在MVC Core中,因此我假设语法保持不变.

The ContentResult class is in MVC Core, so I assume that the syntax remains the same.

这篇关于asp.net mvc核心如何返回Json查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆