Create JavaScript Array in ASP.NET MVC Razor

Let’s you need to populate this variable in javascript-

Divisions= ["Dhaka", "Khulna", "Rajshahi"];

Way 1: Done in javascript tag.

  //first declare an empty array
  var Divisions = []; 
  //Razor Loop
  @foreach (var row in ViewBag.DivisionTable.Rows)

Way 2: Done in C#

string[] Divisions = new string[qty];
//int[] data = new int[qty];

for (int i = 0; i < DivisionQty; i++)
   Divisions[i]= Table.Rows[i]["DivName"].ToString();


//Now in javascript-
var Divisions = @Html.Raw(Json.Encode(ViewBag.Divisions));

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s