JavaScriptServices icon indicating copy to clipboard operation
JavaScriptServices copied to clipboard

Server side rendering window object not rendered

Open jeinz11 opened this issue 9 years ago • 1 comments

hi i have this code in my index method and when i check the page source it doesnt have the window object that i assigned in the globals...but when i switch on using the tag helper its perfectly fine i can see the window object

 public async Task<IActionResult> Index()
    {
        var nodeServices = Request.HttpContext.RequestServices.GetRequiredService<INodeServices>();
        var hostEnv = Request.HttpContext.RequestServices.GetRequiredService<IHostingEnvironment>();

        var applicationBasePath = hostEnv.ContentRootPath;
        var requestFeature = Request.HttpContext.Features.Get<IHttpRequestFeature>();
        var unencodedPathAndQuery = requestFeature.RawTarget;
        var unencodedAbsoluteUrl = $"{Request.Scheme}://{Request.Host}{unencodedPathAndQuery}";

        TransferData transferData = new TransferData();
        transferData.Request = AbstractHttpContextRequestInfo(Request); // You can automatically grab things from the REQUEST object in Angular because of this



        // Prerender / Serialize application (with Universal)

        var prerenderResult = await Prerenderer.RenderToString(
            "/", // baseURL
            nodeServices,
            new JavaScriptModuleExport(applicationBasePath + "/ClientApp/dist/boot-server"),
            unencodedAbsoluteUrl,
            unencodedPathAndQuery,
            // Our Transfer data here will be passed down to Angular (within the main.server file)
            // Available there via `params.data.yourData`
            transferData,
            30000,
            Request.PathBase
        );



        // This is where everything is now spliced out, and given to .NET in pieces
        ViewData["SpaHtml"] = prerenderResult.Html;
        if (prerenderResult.RedirectUrl != null)
        {
            return LocalRedirect(prerenderResult.RedirectUrl);
        }

     
        return View();
    }

and in my view

        <div id="react-app">@Html.Raw(ViewData["SpaHtml"])</div>

but no luck i cant see the window object

jeinz11 avatar Jun 28 '17 03:06 jeinz11

The data you assign to globals will be returned to your .NET code as prerenderResult.Globals. It's up to you to then pass that from your MVC action to your view and render it into the page however you want. That doesn't happen automatically - it's not part of prerenderResult.Html, because it's up to you how you want to serialize it and where you want to inject it into the page.

As an example, you can see the code that the built-in asp-prerender-module tag helper uses to extract and format the data here: https://github.com/aspnet/JavaScriptServices/blob/dev/src/Microsoft.AspNetCore.SpaServices/Prerendering/PrerenderTagHelper.cs#L137

SteveSandersonMS avatar Jun 28 '17 08:06 SteveSandersonMS