简体   繁体   中英

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

You try

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM