简体   繁体   English

如何将 controller 中的数组传递给 cshtml 中的 JS - MVC

[英]How to pass Array in controller to JS in cshtml - MVC

I am a beginner to develop.Net MVC 5 application.我是开发.Net MVC 5 应用程序的初学者。 But I have some problems with passing an array from the controller to JS in cshtml but I don't know how do I do, anyone to inform me?但是我在将数组从 controller 传递到 cshtml 中的 JS 时遇到了一些问题,但我不知道该怎么做,有人告诉我吗? enter image description here在此处输入图像描述

enter image description here在此处输入图像描述

JS: JS:

var areaChartData = {
  labels: ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık'],
  datasets: [{
          label: 'Çıkan Ürün',
          backgroundColor: 'rgba(210, 214, 222, 1)',
          borderColor: 'rgba(210, 214, 222, 1)',
          pointRadius: false,
          pointColor: 'rgba(210, 214, 222, 1)',
          pointStrokeColor: '#c1c7d1',
          pointHighlightFill: '#fff',
          pointHighlightStroke: 'rgba(220,220,220,1)',
          data: [10,10,20,22,23,24,25,26,27,20,10,111]
      }]
}

Controller: Controller:

public ActionResult Index() {

    double[] giren = new double[11];
    return View();
}

How can I post the array sent to "data" in the JS?如何在 JS 中发布发送到“数据”的数组?

You can not directly pass the value from Controller to JS in cshtml part.您不能直接将 Controller 中的值传递给cshtml部分中的JS First bind the cshtml then get the element in DOM , so that DOM will load with the value in cshtml element which is coming from controller.首先绑定cshtml然后获取DOM中的元素,以便DOM将加载来自 controller 的cshtml元素中的值。

Then you can access the value from cshtml element to JS .然后您可以从cshtml元素访问JS的值。 This is the cycle.这就是循环。

You Can refer below article.你可以参考下面的文章。 https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views https://www.pluralsight.com/guides/asp-net-mvc-using-javascript-with-ajax-and-razor-partial-views

I found a solution:我找到了一个解决方案:

controller: controller:

using Newtonsoft.Json;
public ActionResult Index()
    {
       double[] value= new double[13];
       ViewBag.DataPoints1 = JsonConvert.SerializeObject(value);
       return view();
    }

JS JS

 datasets: [
            {
                label: 'Name',
                backgroundColor: 'rgba(210, 214, 222, 1)',
                borderColor: 'rgba(210, 214, 222, 1)',
                pointRadius: false,
                pointColor: 'rgba(210, 214, 222, 1)',
                pointStrokeColor: '#c1c7d1',
                pointHighlightFill: '#fff',
                pointHighlightStroke: 'rgba(220,220,220,1)',
                data: @Html.Raw(ViewBag.DataPoints1)
            },

"data" can call values as ViewBag from controller “数据”可以从 controller 调用值作为 ViewBag

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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