Search code examples
asp.net-mvcrazorhtml-encode

Cannot figure out Html Encoding usage


I'm working on MVC web application. I have a page mix of Razor and JavaScript.

Razor:

@{
    ViewBag.Title = "Edit";
    string initialImage = "<img src='/Site_Data/BIO/Bio.jpg' title='BIO'>";
}

JavaScript:

<script type="text/javascript">
    $("#Photos").fileinput({
        initialPreview: [@initialImage],

What I want is:

<script type="text/javascript">
    $("#Photos").fileinput({
        initialPreview: ["<img src='/Site_Data/BIO/Bio.jpg' title='BIO'>"],

What I get (in source view) is:

<script type="text/javascript">
    $("#Photos").fileinput({
        initialPreview: [&lt;img src=&#39;/Site_Data/BIO/Bio.jpg&#39; title=&#39;BIO&#39;&gt;],

I tried many combinations of HtmlEncode and HtmlDecode (on both Razor and JavaScript section) but could not figure it out. Please advise. Thank you!


Solution

  • by default asp.net mvc will encode your string. to use the unencoded string use Html.Raw(string):

    <script type="text/javascript">
        $("#Photos").fileinput({
            initialPreview: ["@Html.Raw(initialImage)"],