0

I am having an issue pushing a list from my C# model in razor to jquery to play with!

So assume my List is working well and I am able to see the data in razor (Because I can)

I then have the following:

@using Models.DatabaseModel;
@using Newtonsoft.Json;
@{
    Person _Person = ViewBag._Person;
    var json = JsonConvert.SerializeObject(new
    {
        operations = _Person
    });
 }

And then at the bottom I have a javascript loading as so:

    <script type="text/javascript">
        $(document).ready(function () {
            StoreUserInfo("@json");
        });
    </script>

The following calls the javascript correctly, but the string that is passed through to the javascript is full of html characters

An example: "{"operations":{"PersonID":"8"}}"

My jquery is as follows:

function StoreUserInfo(UserObject)
{
    var jsonobj = $.parseJSON(UserObject);
    if (typeof (Storage) !== "undefined") {

    } else {

    }

}

Which errors with the Syntax Error:

Uncaught SyntaxError: Unexpected token & in JSON at position 1

The theory behind this is my C# list pushes a heap of data that I want to store in local storage, I am open to a better method to do this if anyone has it or solutions to my syntax issue I am having.

1
  • Probably UserObject is already contains a JSON object, where $.parseJSON calls toString method which reveals & sign at first place (possibly by &quot;) causing the problem. Can you provide sample of passed string to JS side? Commented May 24, 2017 at 2:59

3 Answers 3

2

Try using this approach. I use this when it's necessary to access my model in javascript.

    <script type="text/javascript">
        var list = '@Html.Raw(Json.Encode(new { operations = ViewBag._Person }))';
        $(document).ready(function () {
            StoreUserInfo(list);
        });
        function StoreUserInfo(UserObject)
        {
            var jsonobj = JSON.parse(UserObject);
            if (typeof (Storage) !== "undefined") {

            } else {

            }    
        }
    </script>
Sign up to request clarification or add additional context in comments.

2 Comments

var jsonobj = JSON.parse(UserObject); won't be needed then I guess, as UserObject is already in Json format.
Thanks for giving me the tip on the HTML Raw, my final solution was changing the javascript call to the following. StoreUserInfo(@Html.Raw(Json.Serialize(_Person))); and then dropping the json ser in the javascript, the object came through perfectly
1

The problem comes from StoreUserInfo call:

$(document).ready(function () {
     StoreUserInfo("@json");
});

The @json part actually defining a JSON object instead of JSON string, since @ sign actually encodes your JSON string to encoded HTML format like this:

&quot;{&quot;operations&quot;:{&quot;PersonID&quot;:&quot;8&quot;}}&quot;

Since it tries to parse & sign in JS object, it throws syntax error.

Instead, use Html.Raw with Json.Encode method like this:

$(document).ready(function () {
     StoreUserInfo("@Html.Raw(Json.Encode(json))");
});

NB: It is better to parse JSON string through a viewmodel property instead generating JSON string inside view like this:

<script type="text/javascript">
    $(document).ready(function () {
        StoreUserInfo("@Html.Raw(Json.Encode(Model.JsonString)");
    });
</script>

Note that in version 3.0 $.parseJSON is deprecated, you can change/remove it since it may be unnecessary to parse already-made JS object.

function StoreUserInfo(UserObject)
{
    // parsing JSON string may be unnecessary here
    if (typeof (Storage) !== "undefined") {
        // do something
    } else {
        // do something
    }
}

Related issues:

JSON to JavaScript, SyntaxError: Unexpected token &

SyntaxError: Unexpected token & in JSON

1 Comment

Your answer was correct, but had to be fair and give it to the first! I am using MVC6 so the Json.Encode was Json.Serialize
0

You can do it like this using @Html.Raw:

<script>
    var person = 
        @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(
           new { Name = "Yoshi", Age = 32 }))
        alert(person.Name);
</script>

Comments

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.