0

I would like to see my controller's variables in the window JavaScript object. I mean, globally, for particular View. For this, I have the following code in the controller:

    public async Task<IActionResult> Create()
    {
        ViewBag.AdvertiserOptions = await _advertiserRepository.Advertisers.ToListAsync();
        ViewBag.CategorieOptions = await _categoryRepository.Categories.ToListAsync();

        return View();
    }

And on the view I have the following (to catch variables):

@section Scripts
{
    <script>
        window.ManuallySending.advertiser_options = 
            JSON.parse(@JsonConvert.SerializeObject(ViewBag.AdvertiserOptions));

        window.ManuallySending.category_options = 
                    JSON.parse(@JsonConvert.SerializeObject(ViewBag.CategorieOptions));

    </script>
}

It gives me the following error:

enter image description here

And in the JS console in my browser:

Uncaught SyntaxError: Unexpected token &

I'm using newtonsoft json library. Here is a link on the documentation

So, why it is happening? How to convert this &quot; to ordinary " for my case?

Update

I have tried this:

@section Scripts
{
    <script>
        window.ManuallySending.advertiser_options = 
            JSON.parse(@Html.Raw(JsonConvert.SerializeObject(ViewBag.AdvertiserOptions)));

        window.ManuallySending.category_options = 
                    JSON.parse(@Html.Raw(JsonConvert.SerializeObject(ViewBag.CategorieOptions)));

    </script>
}

but it gives me new error:

VM191:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () at Create:127

enter image description here

1

1 Answer 1

1

Try using @Html.Raw() your code should be like this

JSON.parse(@Html.Raw(JsonConvert.SerializeObject(ViewBag.AdvertiserOptions)));

Update : for not to having syntax error in javascript you should add a single quotation like the following

JSON.parse('@Html.Raw(JsonConvert.SerializeObject(ViewBag.AdvertiserOptions))');
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you. Almost works. But it gives me new one error. I have updated my question.
add single quotation like the following JSON.parse('@Html.Raw(JsonConvert.SerializeObject(ViewBag.AdvertiserOptions))'); I'll edit my ansower
It gives me new error Uncaught SyntaxError: missing ) after argument list.
sorry you should use single quotation instead of double quotation like this JSON.parse('@Html.Raw(JsonConvert.SerializeObject(ViewBag.AdvertiserOptions))');
Check this, it should solve your problem stackoverflow.com/a/26344334/4749790
|

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.