0

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!

1 Answer 1

1

It's a bit awkward to mix C# control flow with javascript. Try this:

var defaultValue = 'Hello';
var myValue = @Json.Serialize(Model.ValueSpecified) 
  ? @Json.Serialize(Model.ValueToUse) 
  : defaultValue;

This is totally javascript control flow, just with the values coming from Razor.

Sign up to request clarification or add additional context in comments.

1 Comment

I completely agree and was wincing as I typed the js lines inside the razor code. Thanks for the tip!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.