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 ' and "
var String = "@Model.String".replace(/'/g, "'").replace(/"/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.
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 ' and "
var String = "@Model.String".replace(/'/g, "'").replace(/"/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.
Share Improve this question edited Jun 15, 2013 at 13:15 tereško 58.4k25 gold badges100 silver badges150 bronze badges asked Jun 14, 2013 at 8:18 EspenEspen 3,72711 gold badges50 silver badges77 bronze badges3 Answers
Reset to default 13@Html.Raw(yourString)
This should work:
@model Models.Package
<script type="text/javascript">
(function () {
var String = "@Html.Raw(Model.String)";
})();
</script>
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.. :)