I am using the latest SPA template from https://github.com/aspnet/JavaScriptServices
How can I pass a serialized object from MVC to Angular? Is this possible?
I am using the latest SPA template from https://github.com/aspnet/JavaScriptServices
How can I pass a serialized object from MVC to Angular? Is this possible?
At first glance you have two options. If you use server-side rendering, you can use the asp-prerender-data
tag helper, otherwise, you can adopt the classical approach with data attributes.
For example (illustrating both approaches at the same time):
Index.cshtml
<app asp-prerender-module="ClientApp/dist/main-server"
asp-prerender-data='@JavaScriptHelper.Json(this.Model)'
data-serverData='@JavaScriptHelper.Json(this.Model)'>
Loading...
</app>
boot-server.ts
Now in boot-server.ts, if you use server-side prerendering, you can access the passed server data via params.data
. Also here you should pass your server data to the client side (boot-client.ts
) along with the generated html. For example:
setImmediate(() => {
resolve({
html: state.renderToString(),
globals: {
serverData: params.data
}
});
moduleRef.destroy();
});
boot-client.ts
If you use server-side rendering, the passed data (serverData: params.data
) will be attached to the window
object. For example, you could have something like:
interface ServerData{ id: number, name: string};
let serverData : ServerData = JSON.parse((window as any).serverData);
console.log("My data", serverData);
console.log("id", serverData.id);
If you have passed the object via data attributes, then:
interface ServerData{ id: number, name: string};
let root = document.getElementsByTagName('app')[0];
let serverData : ServerData = JSON.parse((root as any).dataset.serverdata);
console.log("My data", serverData);
console.log("id", serverData.id);
JavaScriptHelper.cs
Just a helper class serializing an object to string with some settings. There might be a smarter way, but.....
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public static class JavaScriptHelper{
public static string Json(object obj)
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new JsonConverter[]
{
new StringEnumConverter(),
},
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
return JsonConvert.SerializeObject(obj, settings);
}
}
p.s. Before testing don't forget to run: webpack --config webpack.config.js