简体   繁体   English

如何将数据从 MVC controller 传递到 javascript?

[英]How to pass data from MVC controller to javascript?

I'm starter in programming, I have 2 project which is working like client-server via Rest API.我是编程的初学者,我有 2 个项目,它通过 Rest API 像客户端服务器一样工作。 I want to construct a column chart and all data a List of and ID(participant) and Votes(Total votes) is getting from server where is connection with database.我想构建一个柱形图,所有数据列表和 ID(参与者)和投票(总票数)都是从与数据库连接的服务器获取的。 My problem I have my data I get from the server in method controller, but I can't pass to javascript.我的问题我有我的数据,我是通过方法 controller 从服务器获取的,但我无法传递给 javascript。 I tried with Jquery but no result.我尝试使用 Jquery 但没有结果。 How I can resolve this?我该如何解决这个问题?

public class TestController : Controller
{
    private IVote vote;

    public TestController()
    {
        var bl = new BusinessManager();
        vote = bl.GetVote();
    }

    public IActionResult Index()
    {
        {
            Getstatus();

            return View();
        }
    }
    [HttpGet]
    public async Task<ActionResult> Getstatus()
    {
        var votestatus = new VoteStatus();
        votestatus.Region = 1;
        var query = await vote.VoteStatus(votestatus);
        return Json(query.TotalVotes);
    }
}

My List that contains:我的列表包含:

public class VoteStatistics
    {
        public int IDParty { get; set; }
        public int Votes { get; set; }
    } 

My test view:我的测试视图:

<canvas id="myChart" style="padding: 0;margin: auto;display: block; "></canvas>

Javascript: Javascript:

<script>
    function renderChart(labels, voice) {
        debugger;
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx,
            {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: '# of Votes',
                            data: voice,
                            backgroundColor: [
                                'rgba(255, 99, 132, 0.2)',
                                'rgba(54, 162, 235, 0.2)',
                                'rgba(255, 206, 86, 0.2)',
                                'rgba(75, 192, 192, 0.2)',
                                'rgba(153, 102, 255, 0.2)',
                                'rgba(255, 159, 64, 0.2)'
                            ],
                            borderColor: [
                                'rgba(255, 99, 132, 1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 206, 86, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)'
                            ],
                            borderWidth: 1
                        }
                    ]
                },
                options: {
                    scales: {
                        yAxes: [
                            {
                                ticks: {
                                    beginAtZero: true
                                }
                            }
                        ]
                    }
                }
            });
    }
</script>

I tried to get my List with jquery我试图用 jquery 获取我的列表

<script>$(function(){

    $.ajax({
        type: "GET",                  
        url: '@Url.Action("Getstatus","Test")',
        debugger;
    }).done(function (votings) {
        var labelsArray = [];
        var dataArray = [];
        $.each(votings, function (index, data) {
            labelsArray.push(data.IDParty);
            dataArray.push(data.Votes);
            
        });
        renderChart(labelsArray, dataArray);
    });

});
</script>

You'll need to render the data out in your Razor view as dynamically constructed JavaScript object.您需要在 Razor 视图中将数据呈现为动态构造的 JavaScript object。

ie IE

<script>
    let myJsObj = {
        aStringVar = '@Model.MyStringData'
    };
</script>

Once you've done this, your other JavaScript in the page should be able to access this new object.完成此操作后,页面中的其他 JavaScript 应该能够访问这个新的 object。

For more complex objects you could serialise them to JSON in the controller, store the JSON in a string variable in your view model, then deserialise the JSON in your view... For more complex objects you could serialise them to JSON in the controller, store the JSON in a string variable in your view model, then deserialise the JSON in your view...

<script>
    let myJsObj = JSON.parse('@Model.MyStringData');
</script>

You are making a get request (via ajax) to the GetStatus controller action which is labelled with [HttpPost] .您正在向标有[HttpPost]GetStatus controller 操作发出获取请求(通过 ajax)。 Try to replace it with the [HttpGet] attribute.尝试用[HttpGet]属性替换它。

Do you mean you want to get json data from controller with ajax?If so,you need to use dataType: "json" in ajax so that you can get json data.And here is a demo worked: Do you mean you want to get json data from controller with ajax?If so,you need to use dataType: "json" in ajax so that you can get json data.And here is a demo worked:

Controller: Controller:

public ActionResult GetStatus() {
            return View();
        }
        [HttpGet]
        public async Task<ActionResult> GetData()
        {
            VoteStatistics voteStatistics = new VoteStatistics();
            voteStatistics.IDParty = 1;
            voteStatistics.Votes = 2;
            return Json(voteStatistics);
        }

View:看法:

<h1>GetStatus</h1>
<button onclick="getdata()">getdata</button>
@section scripts{ 
    <script type="text/javascript">
    function getdata() {
        $.ajax({
        type: "GET",
            url: '@Url.Action("GetData","Test")',
            dataType: "json",
    }).done(function (data) {
        alert("IDParty:" + data.idParty + ",Votes:" + data.votes);
    });
    }
    </script>
}

result:结果: 在此处输入图像描述

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

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