PieDev
PieDev

Reputation: 197

.Net Core 2 Convert C# Variable To Javascript In View

I am trying to get a C# variable cSharpString copied over to a JavaScript variable filename in my MVC view.

@{
    ViewData["Title"] = "Title";
}

@section head {

    @{
        string cSharpString = "Hello World";
        <script type="text/javascript">
            var filename = "<%=cSharpString%>";
        </script>
    }
}

When debugging in Chrome and entering the JavaScript variable name the console outputs the C# code instead of the variable name like I would expect.

filename
"<%=cSharpString%>"

Upvotes: 5

Views: 1041

Answers (2)

Tran Audi
Tran Audi

Reputation: 607

You try

<script type="text/javascript">
     var filename = "@cSharpString";
</script>

Upvotes: 0

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

You can use Razor's @ wrapped in quotes like these:

var filename = '@cSharpString';

// alternative
var filename = "@cSharpString";

The <%= cSharpString %> can only used in ASPX (webforms engine) page to render text from variable.

Upvotes: 1

Related Questions