Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

c# - 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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...