如何在ASP.NET MVC/Web控制器中返回JSON? [英] How to return JSON in a ASP.NET MVC/web controller?

查看:309
本文介绍了如何在ASP.NET MVC/Web控制器中返回JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我一直在关注ASP.net MVC/API教程,但在MVC方面我有一个正常工作的控制器.例如,这可以正常工作,并在视图中返回我的数据:

My problem is that I've been following ASP.net MVC/API tutorials I have a working controller in the MVC side of things. For instance this works fine and returns my data in a view:

public class DestinationController : Controller
{
    private ebstestEntities db = new ebstestEntities();

    // GET: Destination
    public async Task<ActionResult> Index()
    {

        return View(await db.CI_DEST_ALL_VARIABLES.ToListAsync());
    }

但是,当我看一下下面的示例(该示例是我在另一个项目上工作的)时,我似乎无法弄清楚如何更改它以使其适合上面的项目控制器.

However when I take a look at the following example, which I had working on another project, I cant seem to work out how to change it to fit in with my project controller above.

// GET: Destination
public async Task<ActionResult> IndexVM()
{
    var model = new BeerIndexVM;

    using (var db = new AngularDemoContext())
    {
        model.Beers = db.Beers.ToList();
    }
    return Json(model, JsonRequestBehavior.AllowGet);
}

推荐答案

由于方法签名为async Task<ActionResult>,因此需要await方法调用. ToList()的异步版本是ToListAsync().因此,只需在该方法前面加上await即可调用该方法,并为您提供await db.Beers.ToListAsync().将该变量分配给您的模型,您应该是金牌.

Because your method signature is async Task<ActionResult>, you need to await a method call. The async version of ToList() is ToListAsync(). So you'll just call that method with the preceding await in front of it giving you await db.Beers.ToListAsync(). Assign that variable to your model, and you should be gold.

完整方法:

// GET: Destination
[HttpGet]
public async Task<ActionResult> IndexVM()
{
    var model = new BeerIndexVM();

    using (var db = new AngularDemoContext())
    {
        model.Beers = await db.Beers.ToListAsync();
    }
    return Json(model, JsonRequestBehavior.AllowGet);
}

我也将在方法上添加一个http动词属性,尽管在此特定情况下不是必需的.

I would also add an http verb attribute on the method, although in this particular instance it's not required.

这篇关于如何在ASP.NET MVC/Web控制器中返回JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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