So I need to pass to a JavaScript function an array of strings in my view based on data from the database. So I have this code in the controller:
string top_six_string = "[";
foreach (ObjectModel om in collection)
{
myProject.Models.BlobFile file = null;
if (om.BlobFile != null)
{
file = om.BlobFile;
}
else if (om.BlobFiles.Count != 0)
{
file = om.BlobFiles.First();
}
if (file != null)
{
top_six_string += " \"" + file.BlobFileID + "\",";
}
}
top_six_string = top_six_string.TrimEnd(',');
top_six_string += "]";
ViewBag.TopSixList = top_six_string;
Now, I don't particularly understand why we have both a BlobFile field and a BlobFiles collection, but that's not that point. The point is, debugging shows that I accurately the get the string I want (of the form ["25", "21", "61", "59"]).
But when running the JavaScript, I got the confusing error "Unexpected character &", and a little source-viewing in Chrome led me to learn that the string came out looking like this:
[ "25", "21", "61", "59"]
So my assumption is that the ViewBag is sanitizing string that it is passed for display in HTML, but obviously that isn't my concern right now. Am I correct in my assumption? Is there another way to pass the view this information? Is there a way I can coerce the string back to quotes afterwards?
The problem is most likely when you output the contents of the ViewBag in your View. By default the Html helpers sanitize output to help protect against injection attacks.
What you want is this when outputting the value in your View: @Html.Raw(ViewBag.TopSixList)
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