1

I am trying to assign a value from a Model into a JavaScript variable. But I have to check a condition before doing so.

Normally, I can assign values using this statement in script : var quantity = '@Model.Quantity'. It works, but I don't know how to do this inside an if loop, like-

<script>
    @if (Model.Count == 0)
    {
        var quantity = 0;
    }
    else
    {
        var quantity = '@Model.Quantity';
    }
</script>

But the statement inside the loop will be rendered as C#. So how do I achieve this ? I have to store the quantity into a JavaScript variable inside if loop.

Thanks :)

2 Answers 2

3

Try this approach:

<script>
    @if (Model.Count == 0)
    {
        @: var quantity = 0;
    }
    else
    {
        @: var quantity = '@Model.Quantity';
    }
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

Can you try as follow:-

<script>
    var quantity = 0;
    @if(Model.Count > 0)
    {
       quantity = 'Model.Quantity';
    }
</script>

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.