Search code examples
c#javascriptasp.net-mvc-4razordygraphs

Passing C# variable using MVC/Razor for use with Dygraph


So here is my problem, and I'm sure it's something very simple. I'm relatively new to Web Development and I'm running into a little problem that I just can't figure out.

I have this code in an MVC view. . .

@{
var data = "";
var count = 1;
foreach (var item in ViewModel.Data)
{
    data += count.ToString() + "," + item.Reading.ToString() + "\n";
    count++;
}

}

I want to pass this 'data' variable to a very tiny script in order to create a graph using Dygraph. This is what I currently have, and believe should work, it doesn't though.

<script type="text/javascript">
g = new Dygraph(document.getElementById("readingGraph"), @data,{ labels: ["Sample Number", "Reading"] });
</script>

I know the script itself will work. If I hard-code some CSV values into a string where @data is, the graph pops up and everything is fine. With the @data there, the graph doesn't load and the script won't run at all (I placed an alert('hi') in there to see if it would pop-up, it didn't).

In addition, I know the string is being 'built' correctly because I have set break points in Visual Studio and checked.

Any help at all would be great guys. Thanks in advance.


Solution

  • I found the issue. A JS literal string cannot span multiple lines (which is how I was feeding it information via the C# created 'data' variable).

    I had to add an '@' in the C# code in order to turn it into a string literal. . .

    foreach (var item in CompletePreview.BatteryData)
    {
        data += count.ToString() + "," + item.Voltage + @"\n"; //note the new @ in front of "\n"
        count++;
    }
    

    The script had to be altered to replace the literal '\n' with one that would break it up in JS.

    g = new Dygraph(document.getElementById("voltGraph"), jsgraphData.replace('\n','\n'), { labels: ["Sample Number", "Voltage"] });
    alert('graphs should follow');
    

    Thanks everybody for the help. I appreciate it greatly.