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 !
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With