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

橙三吉。 提交于 2021-02-18 19:47:24

问题


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.


回答1:


Mixing javascript and Razor requires that you surround your Razor call with any code block

@{ ... } or @if(condition){}, etc.

and putting the code itself in an escaped sequence

@: or the <text> tag.

So, knowing this, you can do something like

<script>
    var jsData = '';
    @{
        <text>
            jsData = '@data';
        </text>
     }

     g = new Dygraph(document.getElementById("readingGraph"), jsData,{ labels: ["Sample Number", "Reading"] });

</script>

Check out Mix Razor and Javascript code and Using Razor within JavaScript




回答2:


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.



来源:https://stackoverflow.com/questions/24811899/passing-c-sharp-variable-using-mvc-razor-for-use-with-dygraph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!