How to return JSON in a ASP.NET MVC/web controller?

后端 未结 2 1525
梦如初夏
梦如初夏 2020-12-12 03:51

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

相关标签:
2条回答
  • 2020-12-12 04:35

    One thing that seems to be missing is your "AcceptVerbs" annotation.

    [AcceptVerbs(HttpVerbs.Get)]
    public async Task<ActionResult> MethodName()
    {
        return json(model, JSonRequestBehavior.AllowGet);
    }
    
    0 讨论(0)
  • 2020-12-12 04:39

    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.

    Complete method:

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

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

    0 讨论(0)
提交回复
热议问题