4

I am trying to pass an array of integers into a data-attribute in ASP.NET Core and I can't get it to work.

Here's what I'm trying to do :

Controller :

public class HomeController : Controller
{
    public IActionResult Index(){
        int[] t = {1, 2, 3, 4};
        ViewBag.t = t;
        return View();
    }
}

Razor View :

@{
    ViewData["Title"] = "Home Page";
}

<label id="intLabel" data-int-array="@(ViewBag.t)">My label</label>

What I've got :

<label id="intLabel" data-int-array="System.Int32[]">My label</label>

What I would like to have :

<label id="intLabel" data-int-array='["1", "2", "3", "4"]'>My label</label>

Thanks !

Tylones
  • 117
  • 10
  • Possible duplicate of [How to print contents of array horizontally?](https://stackoverflow.com/questions/3700448/how-to-print-contents-of-array-horizontally) – Kami Jan 16 '19 at 10:54

1 Answers1

8

One way to do this is to use Newtonsoft.Json

In your Razor code, include @using Newtonsoft.Json .

And then:

<label id="intLabel" data-int-array="@(JsonConvert.SerializeObject(ViewBag.t))">My label</label>

This will produce:

<label id="intLabel" data-int-array="[1,2,3,4]">My label</label>

In your required output, you have requested for string array - in that case you would have to define "t" as a string array in code instead of an int array.

Hope this works for you. If so, please mark this as answer.

Phantom2018
  • 514
  • 1
  • 3
  • 8