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 anot开发者_运维知识库her 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)
Since programmers barely use MVC3 and google shows this page also for Asp core
In ASP.Net Core change this line :
ViewBag.TopSixList = top_six_string;
To
ViewBag.TopSixList = new HtmlString(top_six_string);
And add using Microsoft.AspNetCore.Html; if HtmlString is not accessible.
精彩评论