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?
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?
Share Improve this question edited Dec 18, 2015 at 12:10 Fabio 12k1 gold badge29 silver badges42 bronze badges asked Dec 18, 2015 at 10:46 WillieWillie 3393 silver badges15 bronze badges 10- 1 Which warning do you get? – Domysee Commented Dec 18, 2015 at 10:48
- The warning is syntax error – Willie Commented Dec 18, 2015 at 10:49
- 1 try JSON.parse('@Html.Raw(Json.Encode(Model.ImgLinks))'); – Shekhar Pankaj Commented Dec 18, 2015 at 10:51
- What does this line in the rendered page actually look like? – James Thorpe Commented Dec 18, 2015 at 10:52
- Now, i get no syntax error warning. I think i tried this earlier but i forgot that JSON.parse takes a string as parameter. Thanks @ShekharPankaj – Willie Commented Dec 18, 2015 at 10:54
2 Answers
Reset to default 6To 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>
There is a more elegant solution. You need to serialize your list to JSON:
var imageLinks = @Json.Encode(Model.ImgLinks); // <- annoying syntax error
So you did it right. Now to fix this syntax error I would suggest you to use simple javascript set function:
function set(value) {
return value;
}
var imageLinks = set(@Json.Encode(Model.ImgLinks));
You can find more info about fixing this syntax error here.