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 !

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.