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?
To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With