Technologies:
Tolerim
21 hours ago
Using Razor Variables, how can JavaScript scripts be implemented in a .cshtml file for MVC?
The given code is for a web page that displays information about a horror movie using the TMDb API call. The page includes a JavaScript script that uses the YouTube IFrame Player API to embed the movie trailer. The trailer videoId is assigned to the JS variable 'trailer' which is causing an issue. When the videoId is directly placed in the code, the script works as intended, but assigning it from the C# variable 'movieVideo' from the Model does not work. This issue appeared after merging the code from a different branch. Attempts to use Html.Raw() also failed.
Answers(1)
Tolerim
21 hours ago
Verified Answer
The issue seems to be with the way you are assigning the value of the movieVideo C# variable to the trailer JavaScript variable. Since movieVideo is a string value, you can directly assign that value to trailer without using quotes around it.
So try changing this line:
var trailer = '@movieVideo';
to this:
var trailer = @Html.Raw(Json.Encode(movieVideo));
This will encode the movieVideo string value as a JSON object and pass it to your trailer variable without any issues.
Also, make sure that the movieVideo value is not null or empty before assigning it to trailer, as this could also be a potential cause of the issue.