简体   繁体   中英

How (in Razor) to transfer data from c # array to script (JS) array?

I have this:

<script>var questions = ['A', 'B', 'C'];</script>

And I want something like from that to this:

<script>var questions = [@foreach (var word in Word) { word.abc; } ]</script>

That mistake because I don't know how using '' in Razor

Since you are using razor, you can use this.

<script>
    @{ //example
        var Word = new string[]{ "A", "B", "C" };
    }

    var questions = [@Html.Raw($"'{string.Join("','", Word)}'")];
</script>

Use <text> block to transfer raw strings to js.

<script>
var questions = [];
@foreach (var word in Word) { 
    <text>
  questions.push('@word.abc');
    </text>
} 
</script>

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