So I've read some other threads on this, such as this and this. But I haven't found anything that answers my specific question.
I want to set a JavaScript variable to one of two possible values (let's call them V1 and V2), conditional on the value of some model property. V1 comes from the model and V2 comes from another JavaScript property. Unfortunately because of the way that data is consumed from various APIs, I can't just evaluate which of these two values to use in the controller and hand it to the view. Here is an example of my goal which does not compile:
<script type="text/javascript">
var defaultValue = 'Hello';
@{
if(Model.ValueSpecified)
var myValue = '@(Model.ValueToUse)';
else
var myValue = defaultValue;
}
</script>
So if the model has a ValueSpecified of true and a ValueToUse of Goodbye, then the resulting line of script should be:
var myValue = 'Goodbye';. But if the model ValueSpecified is false, then I'd expect the script line to read var myValue = 'Hello';
I then became acquainted with Html.Raw() and tried this:
<script type="text/javascript">
var defaultValue = 'Hello';
@if(Model.ValueSpecified)
{
@Html.Raw("var myValue = '" + Model.ValueToUse + "';");
}
else
{
@Html.Raw("var myValue = defaultValue;");
}
</script>
And the output works as expected. But this seems very wonky. Is there a better way to handle flow control for js inside of razor?
Thanks for any help!