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)
I managed to do what I needed with
sourcearray = JSON.parse('@Html.Raw(Json.Serialize(allusers))');
Your answer can be simplified from:
sourcearray = JSON.parse('@Html.Raw(Json.Serialize(allusers))');
To:
sourcearray = @Json.Serialize(allusers);
Explanation:
Json.Serialize()
returns IHtmlContent
, which does not need to be wrapped inside @Html.Raw()
to preserve special characters.@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()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With