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?
-
1Which warning do you get?Domysee– Domysee2015年12月18日 10:48:37 +00:00Commented Dec 18, 2015 at 10:48
-
The warning is syntax errorWillie– Willie2015年12月18日 10:49:15 +00:00Commented Dec 18, 2015 at 10:49
-
1try JSON.parse('@Html.Raw(Json.Encode(Model.ImgLinks))');Shekhar Pankaj– Shekhar Pankaj2015年12月18日 10:51:29 +00:00Commented Dec 18, 2015 at 10:51
-
What does this line in the rendered page actually look like?James Thorpe– James Thorpe2015年12月18日 10:52:46 +00:00Commented 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 @ShekharPankajWillie– Willie2015年12月18日 10:54:49 +00:00Commented Dec 18, 2015 at 10:54
2 Answers 2
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>
6 Comments
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.