简体   繁体   中英

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

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

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

[AcceptVerbs(HttpVerbs.Get)]
public async Task<ActionResult> MethodName()
{
    return json(model, JSonRequestBehavior.AllowGet);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM