Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • dominik 711 posts 733 karma points
    Jul 26, 2012 @ 15:42
    dominik
    0

    use brackets in razor script

    Hello together,

    I try to run different javascript lines of code by using razor script:

    <script type="text/javascript">
    jQuery(function(){

    @{
    if(@Model.HasProperty("test") {

        jQuery("#newsticker").webTicker({travelocity:@Model.test});

    } else {

    ...

    }

    }
    </script>

    But I think i am not allowed to use brackets {} within razor script.

    I got it working by pasting the <script> tag directly in if and else

    Any idea how to solve this issue?

  • Funka! 398 posts 661 karma points
    Jul 27, 2012 @ 03:55
    Funka!
    0

    Using brackets inside razor is just fine, but likely the problem you are running into is "context-switching" confusion where it doesn't know which parts are C# and which parts are javascript. (Also you seem to have some mismatched parentheses and braces, and could probably use some quotes inside your webTicker param's object, but let's assume you are paraphrasing here?) Consider the following minor change:

    <script type="text/javascript">
    jQuery(function(){

        @if(Model.HasProperty("test"))
        {
            <text>jQuery("#newsticker").webTicker({"travelocity":"@Model.test"});</text>
        }
        else
        {
            <text>...</text>
        }

    });
    </script>

    However, I usually try to avoid too much interspersion of server-side logic in my javascript code. Usually what I tend to do, is first declare some variables at the top of the script where i can copy all of my server-side variables, and then when I write my javascript, it is completely free of any server-side logic too. In this particular example, it actually simplifies things and avoids the context-switching problems you were likely running into...

    <script type="text/javascript">
    jQuery(function(){
        var test = '@Model.test'; // this is only place where server-side variable is injected. The rest is regular javascript...
        if (test) {
            jQuery("#newsticker").webTicker({"travelocity":test});
        }
        else {
            // ....
        }
    });
    </script>

    Best of luck!

  • Simon 4 posts 24 karma points
    Jul 27, 2012 @ 16:08
    Simon
    0

    In adition to Funka!'s post above you can escape Razor syntax with the much shorter an aesthetically pleasing '@:'

    e.g.

    <script type="text/javascript">
    jQuery
    (function(){

       
    @if(Model.HasProperty("test"))
       
    {
           
    @:jQuery("#newsticker").webTicker({"travelocity":"@Model.test"});
       
    }
       
    else
       
    {
           
    @:...
       
    }

    });
    </script>
Please Sign in or register to post replies

Write your reply to:

Draft