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?

1

2 Answers 2

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)))";
Sign up to request clarification or add additional context in comments.

2 Comments

The first version worked! It just says invalid character on the first (. Why would this be?
@user2206127 Yeah, I just tested here to be sure and I'm getting the correct result.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.