Reputation: 455
I have a view that's building a drop down list based on what's sent from the model.
@{
StringBuilder sb = new StringBuilder("<select id=\"field"+Model.Id+"\">");
sb.Append("<option>Choose...</option>");
foreach(var s in Model.Choices)
{
sb.Append("<option>" + s + "</option>");
}
sb.Append("</select>");
var str = sb.ToString();
}
$("#label" + "@Model.Id").html("@str");
But in the browser, instead of it creating a drop down list, it's actually outputting the entire string "<select id="field3"><option>Choose...</option><option>Movie</option><option>TV Show</option><option>Shorts</option></select>"
Why is it doing this and how can I get it to show the actual drop down list?
Upvotes: 0
Views: 2898
Reputation: 22036
what you need is HtmlString.
@{
StringBuilder sb = new StringBuilder("<select id=\"field"+Model.Id+"\">");
sb.Append("<option>Choose...</option>");
foreach(var s in Model.Choices)
{
sb.Append("<option>" + s + "</option>");
}
sb.Append("</select>");
var str = new HtmlString(sb.ToString());
}
Strings are now automatically Html encoded if they are plain strings but an HtmlString object is rendered as is.
Hope this helps.
Upvotes: 6