Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting C# List<string> To Javascript

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

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

I want a Javascript array or json of the ImgLinks property of my model. I have tried-

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

But i get a syntax error warning. Can anyone please help me out with the conversion to both javascript array and json?

like image 469
Willie Avatar asked Dec 18 '15 10:12

Willie


People also ask

How do you convert C to F easily?

To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.

What is type conversions in C?

In C programming, we can convert the value of one data type ( int, float , double , etc.) to another. This process is known as type conversion.


1 Answers

To get rid of the 'syntax error' you just need to remove ; at the end

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

Despite the warning your code will run fine anyway.

Here's a different kind of solution to the problem if anyone's interested. You can loop through the razor collection and store the values in a Javascript Array like this.

<script type="text/javascript">

    var myArray = [];

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

</script>
like image 130
PsyLogic Avatar answered Oct 14 '22 00:10

PsyLogic