3

This is my Models code:

public class graph_user
{
    public  List<int> year { get; set; }
}

This is my Views code side:

@model  IEnumerable testing.Models.graph_user

function generateChart() {
    var data = new google.visualization.DataTable();
    for (i = 0; i < year.length; i++) {
        data.addColumn('string',);
        data.addRow();
    }
}

Basically I want to obtains the values from list year from within the Models to the javascript which is seen declared in my views.

2
  • Is you model graph_user or IEnumerable<graph_user>? Commented Aug 13, 2015 at 4:38
  • Oops You're right, it's suppose to me @model graph_user thanks ! Commented Aug 13, 2015 at 6:43

1 Answer 1

4

Assuming your model is actually @model graph_user and not @model IEnumerable<graph_user> (your current definition would not compile)

You can assign you models collection to a javascript variable using

var yearList = @Html.Raw(Json.Encode(Model.year))

Then iterate over it using

$.each(yearList, function(index, item) {
  var year = item;
  // do something with it
});

Side note: Recommend you follow normal naming conventions and name your property Years - plural - (not year) and your class GraphUser

Sign up to request clarification or add additional context in comments.

6 Comments

Why do you recommend to represent object as string and than parse it instead of directly representing object in JavaScript?
@AlexeiLevenkov, Not sure what you mean. What would you suggest?
var yearList = @Html.Raw(Json.Encode(Model.year));
I'm guessing I could also use var yearList = @Html.Raw(Json.Encode(Model.year)) and then to display i do yearlist[1] ??
@JohnLington, You can use either the for (i = 0; i < yearList.length; i++) { or the $.each() loop - both will work.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.