mirror of
https://github.com/aspnet/JavaScriptServices.git
synced 2025-12-25 19:17:30 +00:00
Implement and document asp-prerender-data
This commit is contained in:
@@ -81,6 +81,34 @@ If you try running your app now, you should see the HTML snippet generated by yo
|
||||
|
||||
As you can see, your JavaScript code receives context information (such as the URL being requested), and returns a `Promise` so that it can asynchronously supply the markup to be injected into the page. You can put whatever logic you like here, but typically you'll want to execute a component from your Angular 2 / React / etc. application.
|
||||
|
||||
**Passing data from .NET code into JavaScript code**
|
||||
|
||||
If you want to supply additional data to the JavaScript function that performs your prerendering, you can use the `asp-prerender-data` attribute. You can give any value as long as it's JSON-serializable. Bear in mind that it will be serialized and sent as part of the remote procedure call (RPC) to Node.js, so avoid trying to pass massive amounts of data.
|
||||
|
||||
For example, in your `cshtml`,
|
||||
|
||||
<div id="my-spa" asp-prerender-module="ClientApp/boot-server"
|
||||
asp-prerender-data="new {
|
||||
IsGoldUser = true,
|
||||
Cookies = ViewContext.HttpContext.Request.Cookies
|
||||
}""></div>
|
||||
|
||||
Now in your JavaScript prerendering function, you can access this data by reading `params.data`, e.g.:
|
||||
|
||||
```javascript
|
||||
module.exports = function(params) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var result = '<h1>Hello world!</h1>'
|
||||
+ '<p>Is gold user: ' + params.data.isGoldUser + '</p>'
|
||||
+ '<p>Number of cookies: ' + params.data.cookies.length + '</p>';
|
||||
|
||||
resolve({ html: result });
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
Notice that the property names are received in JavaScript-style casing (e.g., `isGoldUser`) even though they were sent in C#-style casing (e.g., `IsGoldUser`). This is because of how the JSON serialization is configured by default.
|
||||
|
||||
**Passing data from server-side to client-side code**
|
||||
|
||||
If, as well as returning HTML, you also want to pass some contextual data from your server-side code to your client-side code, you can supply a `globals` object alongside the initial `html`, e.g.:
|
||||
@@ -245,7 +273,7 @@ At this stage, run `webpack` on the command line to build `wwwroot/dist/main.js`
|
||||
|
||||
You can now run your React code on the client by adding the following to one of your MVC views:
|
||||
|
||||
<div id="my-spa"></div>
|
||||
<div id="my-spa"></div>
|
||||
<script src="/dist/main.js"></script>
|
||||
|
||||
#### Running React code on the server
|
||||
|
||||
Reference in New Issue
Block a user