Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode viewmodel properties to JavaScript in Razor

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)?

like image 290
Marc Avatar asked Jul 17 '26 20:07

Marc


1 Answers

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.

like image 65
marcos.borunda Avatar answered Jul 19 '26 08:07

marcos.borunda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!