Reputation: 47
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?
Upvotes: 2
Views: 819
Reputation: 399
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.
Upvotes: 0
Reputation: 14655
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)))";
Upvotes: 2