【问题标题】:Passing an array into a data-attribute in ASP.NET Core将数组传递给 ASP.NET Core 中的数据属性
【发布时间】:2019-06-10 10:33:00
【问题描述】:

我正在尝试将整数数组传递到 ASP.NET Core 中的数据属性中,但无法正常工作。

这就是我想要做的:

控制器:

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

剃刀视图:

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

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

我有什么:

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

我想要什么:

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

谢谢!

【问题讨论】:

标签: c# html razor asp.net-core


【解决方案1】:

一种方法是使用 Newtonsoft.Json

在你的 Razor 代码中,包含 @using Newtonsoft.Json

然后:

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

这将产生:

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

在您所需的输出中,您已请求字符串数组 - 在这种情况下,您必须在代码中将“t”定义为字符串数组而不是 int 数组。

希望这对你有用。如果是,请将其标记为答案。

【讨论】:

    猜你喜欢
    • 2017-02-21
    • 2023-01-17
    • 2020-06-26
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2020-03-18
    相关资源
    最近更新 更多