Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array into a data-attribute in ASP.NET Core

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 !

like image 394
Tylones Avatar asked Sep 17 '25 04:09

Tylones


1 Answers

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.

like image 200
Phantom2018 Avatar answered Sep 18 '25 16:09

Phantom2018