Question

I'm sending a model to a view that have strings. Those strings are html encoded and I do not need them to be. Any way to send a model to a view without html encoding?

Model:

public class Package
{
    public string String { get; set; }
}

Controller:

public ActionResult GetPackage()
{
    Package oPackage = new Package();
    oPackage.String = "using lots of \" and ' in this string";
    return View(oPackage);
}

View:

@model Models.Package
<script type="text/javascript">
    (function () {
        // Here @Model.String has lots of &#39; and &quot;
        var String = "@Model.String".replace(/&#39;/g, "'").replace(/&quot;/g, "\"");
        // Here String looks ok because I run the two replace functions. But it is possible to just get the string clean into the view?
    })();
</script>

Running the replace functions is a solution, but just getting the string without the encoding would be great.

Was it helpful?

Solution

@Html.Raw(yourString)

This should work:

@model Models.Package
<script type="text/javascript">
    (function () {
      var String = "@Html.Raw(Model.String)";
})();
</script>

OTHER TIPS

Firstly you need to convert the string to Javascript format.
Then you need to prevent MVC from re-encoding it as HTML (because its Javascript, not HTML).

So the code you need is:

@using System.Web

@model Models.Package

<script type="text/javascript">
    var s = "@Html.Raw(HttpUtility.JavaScriptStringEncode(Model.AnyString, addDoubleQuotes: false))";
</script>

As I think this is different than my previous answer, I am putting here another one. System.Web.HttpUtility.JavaScriptStringEncode(Model.String, true);

@model Models.Package
<script type="text/javascript">
    (function () {
      var String = "@System.Web.HttpUtility.JavaScriptStringEncode(Model.String, true)";
})();
</script>

Hope this helps.. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top