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.

<script>
  //first declare an empty array
  var Divisions = []; 
  
  //Razor Loop
  @foreach (var row in ViewBag.DivisionTable.Rows)
  {
     <text>
       Divisions.push('@row["DisionName"].ToString()');
     </text>
  }
</script>

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();
}

ViewBag.Divisions=Divisions;

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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