I'm facing an issue with sending data from my Entity Framework database to a JavaScript script on my webpage. Below is the snippet of code from my MVC Controller:
public ActionResult Index()
{
var wordsToShow = db.Words.Where(w => w.OwnerName == User.Identity.Name); // && DateTime.Compare(w.NextReview, DateTime.Now) <= 0
ViewBag.wordsToShow = HttpUtility.HtmlDecode(new JavaScriptSerializer().Serialize(wordsToShow));
var test = ViewBag.wordsToShow;
return View();
}
In my index.cshtml file, I have included the following code:
<script>
var wordsJson = "@ViewBag.wordsToShow.ToString()";
var wordsAsObject = JSON.parse(wordsJson);
</script>
However, when I run this, I encounter an error message stating:
Invalid character
This error specifically occurs while parsing the JSON string into a JavaScript object. Upon inspection, I noticed that the contents of the "wordsJson" variable in the web browser do not appear as expected.
What steps can I take to resolve this issue and ensure it works correctly?