Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp net core - from model to javascript

I'm writing an asp net core application. What I want to achieve is to read the model inside the view with Javascript. I found this code but when I run it i receive this error:

'IJsonHelper' does not contain a definition for 'Encode' and no extension method 'Encode' accepting a first argument of type 'IJsonHelper' could be found (are you missing a using directive or an assembly reference?)

how can i fix it?

controller

public async Task<IActionResult> Index()
{
    return View(await _context.Bolla.ToListAsync());
}

view

@model IEnumerable<ps0001.Models.Bolla>

<script>
    var bolla = @Html.Raw(Json.Encode(Model));
</script>
like image 423
carlez Avatar asked Apr 24 '17 16:04

carlez


1 Answers

Try using this in your view instead:

@model IEnumerable<ps0001.Models.Bolla>

<script>
    var bolla = '@Html.Raw(Json.Serialize(Model))';
</script>

EDIT:

In order to view the contents, parse the extracted Model using the following:

var parseModel = JSON.parse(bolla);

Then you will be able to use the object and whatever attributes it contains.

like image 149
Sandman Avatar answered Oct 06 '22 22:10

Sandman