Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning the Model to a Javascript variable in Razor

I have a strongly-typed view bound to an object which contains a Collection (list) of some objects. I know Razor gets executed on the server-side when it's generating the page, whereas Javascript variables don't get instantiated until after the page is displayed... but would it somehow be possible to convert the Model (that the view is bound to) or any of its fields to JSON in Razor without resorting to an AJAX call to fetch that data afterwards?

You know, something like...

var myJavascriptVariable = @Model.MyCollection

where @Model.MyCollection is a list of some objects.

Thanks

like image 937
Seriphos Avatar asked Nov 16 '12 15:11

Seriphos


1 Answers

To get json data you can use the following construction:

var jsData = @Html.Raw(Json.Encode(Model.MyCollection));
like image 193
Artem Vyshniakov Avatar answered Oct 21 '22 03:10

Artem Vyshniakov