简体   繁体   中英

ASP.net core 3.1: Serializing a list in model and deserializing in JavaScript

I'm trying to get a list of objects from the model and use it in JavaScript. What is the best method of serializing the List in the Model and deserializing it in the JavaScript code so I can loop through the list in JS? I should be able to save the list in a JavaScript variable.

Model List:

public List<Post> postsList { get; set; }

If you can provide the specific code that would be perfect.

In MVC it is done in a straightforward way (using strongly-typed view or just ViewBag). Let's assume u have 2 models - FooViewModel:

    public class FooViewModel
{
    public int FooId { get; set; }
    public List<BarViewModel> Bars { get; } = new List<BarViewModel>();
}

and BarViewModel:

 public class BarViewModel
{
    public int BarId { get; set; }

    public string BarName { get; set; }

    public string BarTitle { get; set; }

    public int IdFooViewModel { get; set; }
}

Default HomeController have been changed a little bit:

    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);
    }

On a razor backend we construct a javascript object:

@{
    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>
}

Please, notice @Html.Raw tag helper is used reasonably - razor does html-encoding, which corrupts quotation marks of json data. That's why we get rid of html-encoding. But this can be security critical - your client should trust your backend.

Then, client side does deserialize long string literal to get data.

结果]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM