You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Razor中@Html.DisplayFor数据传递至JS并实现图表?

Hey there! Let's break down and solve your two key issues step by step:

1. Fixing the ID Binding Error in Razor

The int i error happens because @Html.DisplayFor's second parameter is meant for template names, not HTML attributes. Passing new { id = "TimeStamp" + i } directly won't work. Instead, wrap the DisplayFor output in a <span> tag and assign the ID to the span:

<td>
    <span id="TimeStamp@(i)">@Html.DisplayFor(modelItem => item.TIMESTAMP)</span>
</td>
<td>
    <span id="Status@(i)">@Html.DisplayFor(modelItem => item.STATUS)</span>
</td>

Razor will correctly parse @(i) as your loop variable, eliminating the error. Also, when fetching values in JavaScript, since these are <span> elements (not inputs), use .textContent instead of .value:

var myTimeStamp = document.getElementById("TimeStamp"+i).textContent;
var myStatus = document.getElementById("Status"+i).textContent;

2. Chart Library Selection Advice

Let's compare the two options you're considering:

  • Google Charts: You're already using its Timeline component, which is a huge win. It's well-maintained, has clear documentation, and the Timeline chart is purpose-built for your use case (visualizing status over time). The only minor downside is relying on Google's CDN, but it's reliable for most production scenarios.
  • Chart.js (a popular jQuery Charts alternative): It's lightweight, highly customizable, and great for standard charts like line/bar graphs. However, it doesn't have a built-in Timeline component—you'd need to use a third-party plugin or build a custom solution, adding extra work.

For your specific need (status timeline visualization), Google Charts is the optimal choice right now—it lets you implement the feature quickly without reinventing the wheel.

Full Modified Code

Here's the complete, fixed Razor view with working chart integration:

@model IEnumerable<PS1619.Models.Status>
@{ ViewBag.Title = "Asset Status History"; }

<h2>History</h2>
<br />
<button type="button" onclick="drawChart()"><b>Graph</b></button>
<br />
<br />

<table class="table">
    <tr>
        <th>Rig Name</th>
        <th>TimeStamp</th>
        <th>Status</th>
        <th></th>
    </tr>
@{ 
    int i = 1; 
    foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.PC_TAG)</td>
            <td>
                <span id="TimeStamp@(i)">@Html.DisplayFor(modelItem => item.TIMESTAMP)</span>
            </td>
            <td>
                <span id="Status@(i)">@Html.DisplayFor(modelItem => item.STATUS)</span>
            </td>
            <td>
                @* @Html.ActionLink("Edit", "Edit", new { id = item.PC_TAG }) | @Html.ActionLink("Details", "Details", new { id = item.PC_TAG }) | @Html.ActionLink("Delete", "Delete", new { id = item.PC_TAG }) *@
            </td>
        </tr>
        i++;
    }
}
</table>

<div id="timeline" style="height: 180px;"></div>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load('current', { 'packages': ['timeline'] });
    
    function drawChart() {
        var container = document.getElementById('timeline');
        var chart = new google.visualization.Timeline(container);
        var dataTable = new google.visualization.DataTable();
        
        dataTable.addColumn({ type: 'string', id: 'Status' });
        dataTable.addColumn({ type: 'date', id: 'Start' });
        dataTable.addColumn({ type: 'date', id: 'End' });
        
        // Dynamically build chart rows from your data
        var chartRows = [];
        var totalItems = @Model.Count();
        for (var i = 1; i <= totalItems; i++) {
            var timeStampText = document.getElementById("TimeStamp"+i).textContent;
            var statusText = document.getElementById("Status"+i).textContent;
            
            // Convert timestamp string to Date object (adjust parsing if your format is non-standard)
            var startTime = new Date(timeStampText);
            // Set end time to next timestamp (or current time if it's the last entry)
            var endTime = i < totalItems ? new Date(document.getElementById("TimeStamp"+(i+1)).textContent) : new Date();
            
            chartRows.push([statusText, startTime, endTime]);
        }
        
        dataTable.addRows(chartRows);
        chart.draw(dataTable);
    }
</script>

Key Improvements:

  • Fixed the ID binding with span tags
  • Added button click handler to trigger chart rendering
  • Dynamically generates chart data from your database records instead of using hardcoded examples
  • Removed duplicate <html>/<head>/<body> tags (which would break your page structure)
  • Added logic to handle end times for each status entry

内容的提问来源于stack exchange,提问作者ARR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:06:40