How to get MVC model strings as plain text in views

Espen picture Espen · Jun 14, 2013 · Viewed 10.4k times · Source

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.

Answer

Paritosh picture Paritosh · Jun 14, 2013
@Html.Raw(yourString)

This should work:

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