Reputation: 637
I am currently attaching html tags to a div using innerHTMl using server side C#. At this point, I am a little bit concerned about innerHTML not been enconded and this might lead to some security exploits.
var myRequestCount = client.GetRequests(id);
var myRequestMsgs = client.GetRequests(id).OrderByDescending(rd => rd.CreatedDate).Take(4);
lblNoOfRequests.Text = myRequestCount.Count().ToString();
if (myRequestMsgs.Count() != 0)
{
StringBuilder sb = new StringBuilder();
sb.Append("<ul style='list-style-type:disc !important'>");
foreach (var requestMsgs in myRequestMsgs)
{
sb.Append("<a href='#' onclick='return openMyRequestRadWindow(" + requestMsgs.RequestNo + " );' style='color:#f60;font-size:12px;line-height:0.5em'>" + MyZimraHelpers.TruncateAtWord(requestMsgs.Subject, 50) + "</a><br/>");
}
myRequestContainer.InnerHtml = sb.ToString();
}
else
{
myRequestContainer.InnerHtml = "No Request was found";
dvMyRequestVwMore.Visible = false;
}
client.Close();
If I use server.htmlencode(sb.Tostring()) everything comes out as plain html tags in the browser same as using innertext. What is the best way to encode the above output.
Thanks
Upvotes: 1
Views: 162
Reputation: 1110
You can write your loop inside the view itself rather than injecting html into the controls from the codebehind. I use this pattern regularly.
<% foreach (var requestMsgs in myRequestMsgs)
{ %>
<a href="#"
onclick="return openMyRequestRadWindow(<%= requestMsgs.RequestNo %>);"
style="color:#f60; font-size:12px; line-height:0.5em; " >
<%= MyZimraHelpers.TruncateAtWord(requestMsgs.Subject, 50) %>
</a><br/>
<% } %>
Upvotes: 1