Caveman
Caveman

Reputation: 7

use condition in cshtml tags

I try to have a condition tag inside my cshtml page

<script type="text/javascript">
var isTrendClicked = false;
function trendChart() {
      $('.sparkline1').sparkline()
}

if ($("#chart-trend").click(function () {
   trendChart();
   isTrendClicked = true;
}));
</script>


<div>
            @if (isTrendClicked)
            { 
            <span class="inlinesparkline"></span>

            <span class="dynamicbar" ></span>
            }
            else { 
            <span class="sparkline1"></span>
            }
</div>

I get an error: error CS0103: The name 'isTrendClicked' does not exist in the current context

How can I fix this?

Thanks :)

Upvotes: 0

Views: 1890

Answers (2)

PSL
PSL

Reputation: 123739

I think you want to do this. You are mising up Javascript varibles with C#.

Your C# code in Razor is executed n the server and html is rendered back. It doesn't know what is isTrendClicked set in javascript which happens when you run it in the browser. c# is dead by then until you make a server call.

 <script type="text/javascript">
   $(function(){
    var isTrendClicked = false;
    $('.inlinesparkline , .dynamicbar').hide(); 

    function trendChart() {
          $('.sparkline1').sparkline()
    }

    $("#chart-trend").click(function () {
       trendChart();
       $('.sparkline1').hide();
       $('.inlinesparkline , .dynamicbar').show(); 
    });
   });
    </script>


    <div>
         <span class="inlinesparkline"></span>
         <span class="dynamicbar" ></span>
         <span class="sparkline1"></span>
    </div>

Upvotes: 1

Mathew Thompson
Mathew Thompson

Reputation: 56429

You're mixing up Razor and JavaScript. Your variable is a JavaScript variable, yet you are trying to access it through Razor. You've also got a click statement wrapped in a dodgy if statement.

I think this is what you are trying to achieve:

<script type="text/javascript">
    var isTrendClicked = false;

    $(function () {
        $(".inlinesparkline, .dynamicbar").hide();
    });
    function trendChart() {
        $('.sparkline1').sparkline()
    }

    $("#chart-trend").click(function () {
        trendChart();
        isTrendClicked = true;
        $(".inlinesparkline, .dynamicbar").show();
        $('.sparkline1').hide();
    });
</script>


<div>
    <span class="inlinesparkline"></span>
    <span class="dynamicbar" ></span>
    <span class="sparkline1"></span>
</div>

Upvotes: 1

Related Questions