Is there a way to assign the html from a razor page to a javascript variable?

56 Views Asked by At

I have a Razor page with 4 text boxes and a button that creates an additional text box below the other boxes.

When the user clicks the button, a javascript function addNewSection() is triggered and the new text section is inserted to the page.

function addNewSection() {
    var section = document.getElementById("lastTextBox");
    var newSection = `<div> razor page content here. </div>`
    section.insertAdjacentHTML('afterend', newSection);
    
}

This function works when I directly write my razor page content into var newSection. However, the actual razor page content is kind of long. Is there a neater way to do this?

I tried putting the page content into a new razor page "Section.cshtml" and setting var newSection equal to that (see below). But I'm getting an error "CS1963: An expression tree may not contain a dynamic operation". Any idea how I can do something similar to this? I would rather not put a whole cshtml page into my js function. Thanks!

var newSection = @RenderPage("~/Views/Section.cshtml);
1

There are 1 best solutions below

1
Dimitris Maragkos On

Use the PartialAsync HTML Helper:

@section Scripts {
    <script>
        var newSection = "@(await Html.PartialAsync("~/Views/Section.cshtml"))";
    </script>
}

Documentation