5

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%>"

2 Answers 2

1

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.

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

Comments

0

You try

<script type="text/javascript">
     var filename = "@cSharpString";
</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.