开发者

How can I access ViewData in a PartialView from jQuery in MVC?

I have a View loading a PartialView via jQuery. The PartialView has ViewData that the jQuery needs to access, but I can't seem to get to it from the jQuery. The code below uses the HighChart jQuery plugin (and it is just test code taken from the HighChart example page):

<script type="text/javascript">
        var chart1; // globally available
        $(document).ready(function () {
            $('#reportButton').click(function (event) {
                var actionUrl = '<%= Url.Action("UserReport") %>';
                var customerId = $('#customersId').val();
                var month = $('#monthsId').val();
                var employees = '<%= ViewData["Employees"] %>'
                alert(employees);
                $.get(actionUrl, { customerId: customerId, month: month }, function (data) {
                    $('#result').html(data);
                    getHighChart();
                });
            });
        });

        function getHighChart() {
            var employees = '<%= ViewData["Employees"] %>'
            alert(employees);
            chart1 = new Highcharts.Chart({
                chart: {
                    renderTo: 'chart-container-1',
                    defaultSeriesType: 'bar'
                },
                title: {
                    text: 'Fruit Consumption'
                },
                xAxis: {
                    categories: [employees]
                },
                yAxis: {
                    title: {
                        text: 'Fruit eaten'
                    }
                },
                series: [{
                    name: 'Jane',
                    data: [1, 0, 4]
              开发者_Go百科  }, {
                    name: 'John',
                    data: [5, 7, 3]
                }]
            });
        }


    </script>

This jQuery is in the main view, because I don't know how I could put it in the PartialView with the document ready function. But by putting the call to the HighChart function in the callback of the get() function it works in the partial view. But accessing the ViewData doesn't...

How can I achieve this? I need to get the data from the PartialView action method in order to populate the HighChart data...


The problem is the way ASP.NET traverses the HTML document when rendering.

Even though you have this code executing after the $.get call has finished:

var employees = '<%= ViewData["Employees"] %>'

The ViewData property will get evaluated render-time (e.g before this code is executed).

What i recommend:

Declare a hidden field in your partial view, and place the ViewData in there:

<input type="hidden" id ="Employees_ViewData" value="<%: ViewData["Employees"] %>" />

That will get evaluated when the partial view is rendered.

Then you can access it via jQuery:

var employees = $('#Employees_ViewData').val();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜