【问题标题】:Graph not displaying in MVC Core图表未在 MVC Core 中显示
【发布时间】:2020-10-06 11:55:29
【问题描述】:

你好可爱的聪明人,我希望你能帮助我完成我正在做的一个 Graph 项目。我发现了一些用于创建图形的漂亮代码here 我正在使用的部分是“来自数据库的数据”,在 MVC Core 项目中,调试时我可以在视图中看到数据库中的值已成功输入到ViewBag.DataPoints 但未显示图表。 我在 Visual Studio 2019 中使用 .NET Core 3.1。 我将非常感谢您能提供的任何帮助。 谢谢一百万。

型号:

public class Point
    {
        [Key]
        public int x { get; set; }
        public Nullable<int> y { get; set; }
    }

上下文:

public class DataPointsDB : DbContext
    {
        public DataPointsDB(DbContextOptions<DataPointsDB> options)
            : base(options)
        {
        }
    
        public virtual DbSet<Point> Points { get; set; }
    }

控制器:

public class PointsController : Controller
    {
        private readonly DataPointsDB _db;

        public PointsController(DataPointsDB db)
        {
            _db = db;
        }
        public IActionResult Index()
        {
            IEnumerable<Point> objList = _db.Points;
            return View(objList);
        }

        public IActionResult Create()
        {
            ViewData["x"] = new SelectList(_db.Points, "x", "y");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("x,y")] Point point)
        {
            if (ModelState.IsValid)
            {
                _db.Add(point);
                await _db.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["x"] = new SelectList(_db.Points, "x", "y", point.x);
            return View(point);
        }

        // GET: HowTo
        public ActionResult DataFromDataBase()
        {
            try
            {
                ViewBag.DataPoints = JsonConvert.SerializeObject(_db.Points.ToList(), _jsonSetting);

                return View();
            }
            catch (EntityException)
            {
                return View("Error");
            }
            catch (System.Data.SqlClient.SqlException)
            {
                return View("Error");
            }
        }

        JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };


    }

查看:

@model IEnumerable<Test_Chart.Models.Point>


<div id="chartContainer"></div>

<script type="text/javascript">
    var result = @Html.Raw(ViewBag.DataPoints);
    var dataPoints =[];
    for(var i = 0; i < result.length; i++){
        dataPoints.push({label:result[i].x, y:result[i].y});
    }

    $(function () {
        var chart = new CanvasJS.Chart("chartContainer", {
            theme: "light2",
            zoomEnabled: true,
            animationEnabled: true,
            title: {
                text: "Line Chart with Data-Points from DataBase"
            },
            data: [
            {
                type: "line",

                dataPoints: dataPoints,
            }
            ]
        });
        chart.render();
    });
</script>

我已经添加了 _Layout 中的&lt;script src="https://canvasjs.com/assets/script/canvasjs.min.js"&gt;&lt;/script&gt;

再次感谢 x

【问题讨论】:

  • 你知道js中的关键字“debugger”对吧?如果没有在您上方放置调试器行$(function () {,请检查您的数据是否正确。打开浏览器并让调试器打开 f12
  • 包含js错误并添加html查看
  • Seabizkit,非常感谢您回复我。我不知道,谢谢!你是绝对正确的,这就是问题所在,当我 f12 告诉我“未捕获的 ReferenceError:$ 未定义”时。我还有脚本的“加载资源失败”-modernizr 2.6.2.js 和 font-awesome.min.css。您对我如何解决这些问题有什么建议吗?
  • 老兄!我搞定了,非常感谢!!!我把我的功能东西放在这个小东西里面,它就成功了!惊人的!再次感谢! @section Scripts { &lt;script&gt; $(function () { alert("Test"); }); &lt;/script&gt; }

标签: c# model-view-controller .net-core graph canvasjs


【解决方案1】:

仅供您学习....

//this is not needed as we not doing anything, if you want the chart to 
//happen when the page is loaded then add "renderChart();" inside
//otherwise delete and add onclick to some element with "renderChart();"
$(function () {
   
   //this is short hand for saying when the doc is finished loading... run this.
   
});

//out side of function so its global, 
//example: not what I'm suggesting...
// trying to show you the importance of do something when 
// we have the data... 
var dataPoints =[];
function renderChart1() {

   
    var chart = new CanvasJS.Chart("chartContainer", {
        theme: "light2",
        zoomEnabled: true,
        animationEnabled: true,
        title: {
            text: "Line Chart with Data-Points from DataBase"
        },
        data: [
        {
            type: "line",

            dataPoints: dataPoints,
        }
        ]
    });
    chart.render();

}

//now you can not call renderChart1() as there are no dataPoints so lets fetch them 
//https://www.w3schools.com/jquery/jquery_ref_ajax.asp

$.get("http://localhost:64160/DataFromDataBase", function(data){
    
    //when we have the data set it. this is why we made it global
    //a little confusing but was trying to show smaller steps
   // to get the version below altho i think i my have just made it more confusing
    dataPoints = data;
    renderChart1();
    
});


//better version is.... its much easier to understand 
//-----------------------------------------------

function renderChart() {
   
   $.get("http://localhost:64160/DataFromDataBase", function(data){
    
        //data could be a more complex object instead of just the dataPoints

        var chart = new CanvasJS.Chart("chartContainer", {
            theme: "light2",
            zoomEnabled: true,
            animationEnabled: true,
            title: {
                text: "Line Chart with Data-Points from DataBase"
            },
            data: [{
                type: "line",
                dataPoints: data,
            }]
        });
        chart.render();
    
    });
   
}
//-----------------------------------------------

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多