2

Using ASP.net MVC 3/Razor, how can I include a boolean model property inside a script tag? Here is what I have:

<script type="text/javascript">
    $(document).ready(function () {
        var claimFlagged = "@Model.Flagged"; 
        // More javascript

How would I set claimFlagged to the value in Model.Flagged?

user2206127
  • 47
  • 1
  • 6
  • 1
    possible duplicate of [using razor within javascript](http://stackoverflow.com/questions/4599169/using-razor-within-javascript) – Yurii Dec 22 '13 at 21:00

2 Answers2

2

This will do what you want:

var claimFlagged = @(Html.Raw(Json.Encode(Model.Flagged)));

If you simply try to use something like this:

var claimFlagged = @(Model.Flagged);

it will actually generate True or False (note the capitalised T and F), rather than the more natural lowercase versions. Using the @(Html.Raw(Json.Encode(...))) method results in the correct lowercase output.

I've made the assumption that you want to work directly with bools, rather than strings, in your JavaScript code. If you do actually want the output to be a string instead (i.e. "true" or "false"), simply surround the code with quotation marks:

var claimFlagged = "@(Html.Raw(Json.Encode(Model.Flagged)))";
John H
  • 14,422
  • 4
  • 41
  • 74
0

Have you tried removing the quotes:

<script type="text/javascript">
    $(document).ready(function () {
        var claimFlagged = '@(Model.Flagged)'; 
        // More javascript

Razor wont bind the property if quoted.

GitaarLAB
  • 14,536
  • 11
  • 60
  • 80
Laird Streak
  • 397
  • 5
  • 8