Search code examples
javascriptc#razord3.jsrazorengine

RazorEngine evaluation issue with .js code


I am using RazorEngine to evaluate some JavaScript code and I ran into an issue where it fails to compile. Here's an example:

var someBarChart = d3.select("@Model.DivId").append("svg")
.attr("width", barChartWidth + barChartMargin.left + barChartMargin.right)
.attr("height", barChartHeight + barChartMargin.top + barChartMargin.bottom)
.append("g")
.attr("transform", "translate(" + barChartMargin.left + "," + barChartMargin.top + ")");

The culprit here is "" marks around @Model.DivId. Can somone point me to a way to evaluate that particular example?

I am expecting this result:

var someBarChart = d3.select("someDivId").append("svg")
.attr("width", barChartWidth + barChartMargin.left + barChartMargin.right)
.attr("height", barChartHeight + barChartMargin.top + barChartMargin.bottom)
.append("g")
.attr("transform", "translate(" + barChartMargin.left + "," + barChartMargin.top + ")");

Also, it fails on me when I try to evaluate something like this:

@Model.BarChartName.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + barChartHeight + ")")
.call(xAxis);

In this case I was expecting a result like this:

someBarChart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + barChartHeight + ")")
.call(xAxis);

Like I mentioned I am using RazorEngine and its configured by default to decode Html. I also tried a case of using var someBarChart = d3.select("@Raw(Model.Div)").append("svg") but that fails to evaluate as well.

All ideas are appreciated. Thank you,


Solution

  • Instead of double quotes, use single quotes when you want to use the razor value as a string in javascript:

    d3.select('@Model.DivId')