Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'IJsonHelper' does not contain a definition for 'Encode'

I want to convert a list of strings to a javascript array in my view, and I've found the below suggestion in a few places on the internet:

@model IEnumerable<DSSTools.Models.Box.BoxWhiteListUser>

@{
    var boxManager = new DSSTools.Managers.BoxManager();
    var allusers = boxManager.GetAllUsersAsync().Result.Entries.ToList().Select(u => u.Login);
}

@section Scripts {
    <script>
        var sourcearray = null;

        $(document).ready(function () {
            var arr = JSON.parse('@Html.Raw(Json.Encode(@allusers))');
        });
    </script>
}

However, I just get an annoying

'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 is this possible?

I also tried simply calling

var arr = JSON.parse('@Html.Raw(allusers)');

But then I get this error in the console

VM189:1 Uncaught SyntaxError: Unexpected token S in JSON at position 0
    at JSON.parse (<anonymous>)
    at HTMLDocument.<anonymous> (whitelist:107)
    at fire (jquery.js:3182)
    at Object.fireWith [as resolveWith] (jquery.js:3312)
    at Function.ready (jquery.js:3531)
    at HTMLDocument.completed (jquery.js:3547)
like image 284
Bassie Avatar asked Apr 27 '18 06:04

Bassie


2 Answers

I managed to do what I needed with

sourcearray = JSON.parse('@Html.Raw(Json.Serialize(allusers))');
like image 179
Bassie Avatar answered Sep 19 '22 13:09

Bassie


Your answer can be simplified from:

sourcearray = JSON.parse('@Html.Raw(Json.Serialize(allusers))');

To:

sourcearray = @Json.Serialize(allusers);

Explanation:

  1. Json.Serialize() returns IHtmlContent, which does not need to be wrapped inside @Html.Raw() to preserve special characters.
  2. The text returned by @Json.Serialize() is already valid javascript object syntax. You're better off using it as is, rather than converting it to a string by wrapping it in quotes and then converting that string to an object via JSON.Parse().
like image 25
MarredCheese Avatar answered Sep 16 '22 13:09

MarredCheese