当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net mvc - In Javascript in a MVC Razor, replace a keyword with a value from the model

问题描述:

When you have some JavaScript on an MVC razor view is it possible to do a model variable replacement in the middle of a multipart statement.

To clarify I have the code

<script>

function drawChart() {

$.post('@Url.Content("~/Home/GetDataAssets")', function (d) {

...

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

chart.draw(data, options);

});

};

where I want the type of graph that is displayed to come from the model. So the chart line would have to look something like

var chart = new [email protected](document.getElementById('chart_div'));

Where LineChart has been replaced by @Model.ChartType

This obviously gives the error

ChartType is being used like a method

Is there a way to make this substitution?

网友答案:

As @stephen-muecke said the razor code is parsed on server side and the javascript code on client side.

If Model.ChartType returns a string, i.e. LineChart, you only need to output the paranthesis and the content of it (...) as text.

To do this you have to add @{<text> ... </text>} to output plain text, like below

var chart = new [email protected]@{<text>(document.getElementById('chart_div'));</text>}

The result of client side will be, with my example

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
分享给朋友:
您可能感兴趣的文章:
随机阅读: