我正在尝试从模型中获取对象列表,并在JavaScript中使用它。在模型中序列化列表并在JavaScript代码中反序列化它以便我可以在JS中循环列表的最佳方法是什么?我应该能够将列表保存在一个JavaScript变量中。
型号列表:
public List<Post> postsList { get; set; }
如果您可以提供特定的代码,这将是完美的。
发布于 2020-04-17 01:06:18
在MVC中,这是以一种直接的方式完成的(使用强类型视图或仅使用ViewBag)。假设你有两个模型- FooViewModel:
public class FooViewModel
{
public int FooId { get; set; }
public List<BarViewModel> Bars { get; } = new List<BarViewModel>();
}
和BarViewModel:
public class BarViewModel
{
public int BarId { get; set; }
public string BarName { get; set; }
public string BarTitle { get; set; }
public int IdFooViewModel { get; set; }
}
默认HomeController已稍作更改:
public IActionResult Index()
{
var vm = new FooViewModel
{
FooId = 1,
Bars =
{
new BarViewModel {BarId = 1, BarName = "First Bar", BarTitle = "I am here!", IdFooViewModel = 1},
new BarViewModel {BarId = 2, BarName = "Second Bar", BarTitle = "Me too!", IdFooViewModel = 1}
}
};
return View(vm);
}
在剃刀后端,我们构造一个javascript对象:
@{
ViewData["Title"] = "Home Page";
}
@using System.Collections.Specialized
@using System.Text.Json
@model FooViewModel
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Index works!</p>
</div>
@section Scripts {
<script>
var vm = window.viewModel = JSON.parse('@Html.Raw(JsonSerializer.Serialize(Model))');
console.dir(vm);
</script>
}
请注意,@Html.Raw
标签助手被合理地使用了- razor做了html编码,这破坏了json数据的引号。这就是我们去掉html编码的原因。但这可能是安全关键--你的客户应该信任你的后端。
然后,客户端对长字符串进行反序列化以获取数据。
https://stackoverflow.com/questions/61261277
复制