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

Aleksej_Shherbak
  • 2,757
  • 5
  • 34
  • 71
  • 1
    Does this help you in any way? https://stackoverflow.com/questions/35105587/how-does-html-raw-mvc-helper-work – Caramiriel Nov 16 '19 at 09:40

1 Answers1

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))');