8

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>

1 Answer 1

22

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.

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

4 Comments

Thank you sandman. I tried with --- var model = @Html.Raw(Json.Serialize(Model)); alert(model[0].Anno); --- and now in the alert I got "undefined"
In order to access the variable, you may have to parse. Try: var parseModel = JSON.parse(bolla); and use the console window to view the result.
Thanks @Sandman, I've been tearing my hair out for the last few hours, this sorted my issue!
When I tried var parseModel = JSON.parse(bolla); and I got the following error Uncaught SyntaxError: JSON.parse: bad control character in string literal at line 1 column 39 of the JSON data <anonymous> debugger eval code:1 <anonymous> localhost:9318/Controller/Action?userID=1:370 jQuery 13

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.