Convert C # list <string> to Javascript

I want to convert the Model property of a List type to a Javascript variable used in the same view. This is my model:

 public string Title { get; set; }
 public string Description { get; set; }
 public List<String> ImgLinks { get; set; }

I need a Javascript or json array of the ImgLinks properties of my model. I tried -

var imageLinks = @(Html.Raw(Json.Encode(Model.ImgLinks)));

But I get a syntax error warning. Can someone help me with converting to javascript array and json?

+4
source share
2 answers

You can scroll through the razor collection and save the values ​​in a Javascript array.

<script type="text/javascript">

    var myArray = [];

    @foreach (var link in Model.ImgLinks)
    {
        @:myArray.push("@link");
    }

    alert(myArray);

</script>
+3
source

There is a more elegant solution. You need to serialize your list in JSON:

var imageLinks = @Json.Encode(Model.ImgLinks); // <- annoying syntax error

, . , , javascript:

function set(value) {
    return value;
}

var imageLinks = set(@Json.Encode(Model.ImgLinks));

.

+1

Source: https://habr.com/ru/post/1620724/


All Articles