0

I'm working with Chart.js. I require -

labels : ["Jan","Feb","Mar","Apr","May","Jun","Jul"],

In my controller code I'm doing this-

   string[] Labels = new string[tbl.Rows.Count];
   for (int i = tbl.Rows.Count-1; i >0 ; i--)
   {
       Labels[i] = Convert.ToDateTime(tbl.Rows[i][0]).ToString("MMM") ;
   }

   Labels[0]= Convert.ToDateTime(tbl.Rows[0][0]).ToString("MMM") ;
   ViewBag.ChartLabel = Labels;

Everything is good till this point.

Problem arises when I want to use that value in razor page.

<script>
   labels : [], //How can i use ViewBag.ChartLabel here?
</script>

1 Answer 1

3

The most easy way to do this is to insert the values in array.

<script>
var labels = [];
@foreach(var label in ViewBag.ChartLabel)
{
    <text>
        labels.push('@label');
    </text>
}
</script>

You can find here more ways to convert, the one that I think it's the best

var labels = @Html.Raw(Json.Encode(ViewBag.ChartLabel));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.