HTML.Raw not rendering <script> tags

Viewed 39

I'm trying to use html.Raw with some content I get from the server , it is a html page with JavaScript embedded , something like this :

<title>Footer</title>
<script>alert("hi")</script>
<style>.custom-footer-wrapper {
    margin-top: -12px;
    background-color: #231f20;
    color: #fff;
    padding: 48px;
    min-height: 300px
}

</style>
<div class="custom-footer-wrapper"><div class="row"><div class="logo col-md-2 col-xs-12">

</div>

when I render the html.raw with that string , is displaying all the html except the script tags, what I'm missing?

2 Answers

If your layout contains @await RenderSectionAsync("Scripts", required: false),you can try to use the following code in your view:

@section Scripts{
    <script>
       $(function(){
           alert("hi");
       }) 
    </script>
}

Try to use F12 developer tools to check if there has any error in the Console panel? Besides, you can also use the Elements tools to check whether the <Script> content is add to the dom?

Based on your code and description, I create a Razor page with the following code, it seems that every thing works well.

About.cshtml.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorAPP.Pages
{
    public class AboutModel : PageModel
    {
        [BindProperty]
        public string HtmlString { get; set; }
        public void OnGet()
        {
            HtmlString = "<title> Footer </title><script> alert(\"hi\") </script> <style>.custom-footer-wrapper{margin-top:-12px; background-color:#231f20; color:#fff; padding:48px; min-height:300px}</style> <div id=\"divcontainer\" class=\"custom-footer-wrapper\"><div class=\"row\"><div class=\"logo col-md-2 col-xs-12\"><span>Content</span></div></div></div>";
        }
    }
}

About.cshtml:

@page
@model RazorAPP.Pages.AboutModel

@Html.Raw(Model.HtmlString)

Then, the result as below:

enter image description here

Related