c# - foreach or ToArray inside a section, with js variable error -



c# - foreach or ToArray inside a section, with js variable error -

i'm trying foreach in section in mvc 4. can't acquire scope of js variable. happens here wont recongnise images within foreach. ideas on how solve it?

@section scripts { <script type="text/javascript"> var images = ""; @foreach (var item in model.images) { //it not know images varable here images += string.format("[{0}/{1}],", "path", item); } </script> }

i'm trying without success

@section scripts { <script type="text/javascript"> //statement not terminated var images = @model.images.toarray() console.log(images); </script> }

edit i'm populating image names in controller , passing view.

public class imageviewmodel { public string[] images { get; set; } }

you need switch html (js in case) @: razor again

@section scripts { <script type="text/javascript"> var images = ""; @foreach (var item in model.images) { //it not know images varable here @:images += "@string.format("[{0}/{1}],", "path", item)"; } </script> }

otherwise assumes images server-side c# variable, instead of client side content.

to reply comment, want wind this:

<script type="text/javascript"> var images = ""; images += "imagename1"; images += "imagename2"; images += "imagename3"; images += "imagename4"; </script>

so working backwards that, here pseudo script.

<script type="text/javascript"> var images = ""; // loop start here images += "@server value here"; // loop end here </script>

if have looks code within @foreach{} code block, assume server-side code.

@foreach (var item in model.images) { // "must" local images variable in razor code block! images += @string.format("[{0}/{1}],", "path", item); // wrong! }

the @: escape sequence tells razor treat next markup , not code. @(expression) injects server side value client markup. quotes needed client markup constants.

slicker version: @section scripts { <script type="text/javascript"> var images = "@string.join(",", model.images)"; console.log(images); </script> }

c# jquery asp.net-mvc-4 razor

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -