3

I have a simple ViewModel:

public class IndexViewModel
{
    public bool ShowWelcomeMsg { get; set; }
}

And in my view I need this property in JS:

<script type="text/javascript">
    var ShowWelcomeMsg = @Model.ShowWelcomeMsg;
</script>

But that's not correct because it outputs False instead of false but anyway, the question is more generic because I want to know the solution for int, string, etc as well:

What is the correct way to encode a viewmodel property to use it in JavaScript (in Razor)?

Marc
  • 6,749
  • 9
  • 47
  • 78

2 Answers2

5

This should do the work:

<script type="text/javascript">
    var ShowWelcomeMsg = @Html.Raw(Model.ShowWelcomeMsg);
</script>

You should serialize first your data. Instead of passing a boolean, you should pass a string with json notation:

public class IndexViewModel
{
    public string ShowWelcomeMsg { get; set; }
}

In order to serialize to json you should do:

public ActionResult Index()
{
    var serializer = new JavaScriptSerializer();
    var vm = new IndexViewModel
    {
         ShowWelcomeMsg = serializer.Serialize(true)
    };
    return View(vm);
}

This way you can even serialize a whole C# Object and use it as any other object in JavaScript.

marcos.borunda
  • 1,486
  • 1
  • 17
  • 34
  • Thank you very much, that's a good approach, I think I will build a custom html helper which will encode it to json. I absolutely don't want to do that in the controller or the viewmodel. I'm just wondering why this is not build-in or I'm unable to find it... – Marc Mar 16 '12 at 18:57
  • Sure! you don't want that code neither in your controller nor viewmodel, a html helper sounds like a clean approach, glad my answer helped you – marcos.borunda Mar 16 '12 at 19:25
0

You could just handle the conversion yourself:

<script type="text/javascript">
    var ShowWelcomeMsg = @(Model.ShowWelcomeMsg ? "true" : "false");
    var WelcomeMsg = "@Model.WelcomeMsg.Replace("\r\n", "<br />")";
</script>
mgnoonan
  • 7,060
  • 5
  • 24
  • 27