r/dotnet•
spicypuma69

Passing Data server-side to javascript

Hello, this is a best practices question regarding methods to pass data from the server to javascript. A common use case (the reason I am asking) would be to pass the model into a React.js component.

The method I have been using for a while is based on how I noticed ReactJS.Net is passing data in its Html.React() method:

<!-- Render the component server-side, passing initial props -->
@Html.React("CommentsBox", new { initialComments = Model.Comments })     

Which produces:

<script>ReactDOM.render(React.createElement(CommentsBox, {"initialComments":[ { "Author":{ "Name":"Daniel Lo Nigro", "GithubUsername":"Daniel15" }, "Text":"First!!!!111!" }, { "Author":{ "Name":"Daniel Lo Nigro", "GithubUsername":"Daniel15" }, "Text":"First!!!!111!" } ],"page":1}), document.getElementById("react_G8lq1W0x0Ch7yp3hxVfbA"));  

This can of course get to be very long depending on the amount of data that you are passing into the component. When working on projects I've been using this helper method to produce the same thing: https://gist.github.com/AsifMushtaq/8931990

My question is, is this best practice for getting the data from the server to the client on initial load? It feels dirty to me when looking at the source and seeing a 3000+ character json string but I can't see any other way to do it without just doing ajax calls on the initial load of the page. Any other thoughts/caveats with this approach?

Thanks!

Posted Apr 26, 2017, 5:22 PM UTC

17
Loading comments…