How to populate google charts using data from database created via code first - ASP.Net MVC

后端 未结 2 858
庸人自扰
庸人自扰 2020-12-21 08:33

I want to replace the hard coded data in the code below with data from my database that I\'ve created using the Code First approach.

However, I literally have no ide

2条回答
  •  自闭症患者
    2020-12-21 09:14

    While you could easily generate strings from your entities I am going to use Ajax and JSON as an alternative.

    Imaging you have entity model like this:

    public class Product
    {
        public int ID {get; set; }
        public int Year { get; set; }
        public int Purchase { get; set; }
        public int Sale { get; set; }
    }
    

    And in your DbContext is something like this:

    public class Mycontext:DbContext
    {
        public IDbSet Products { get; set; }
        // other sets 
    }
    

    Now in action method you could remove GetChartData() since we are going to get chart data from Ajax call.

    public ActionResult Index()
    {
        ProductModel objProductModel = new ProductModel();
        objProductModel.YearTitle = "Year";
        objProductModel.SaleTitle = "Sale";
        objProductModel.PurchaseTitle = "Purchase";
        return View(objProductModel);
    }
    

    Add a new action method to get data form Ajax call:

    // in real world you may add some parameters to filter your data  
    public ActionResult GetChart()
    {
        return Json(_myDB.Products
            // you may add some query to your entitles 
            //.Where()
            .Select(p=>new{p.Year.ToString(),p.Purchase,p.Sale}),
                JsonRequestBehavior.AllowGet);
    }
    

    Now your view could be like this:

    
    

提交回复
热议问题