开发者

string with <> around it not displaying when HTML rendered using ASP.NET MVC?

I have an MVC app. In one of the ASPX views I have a select drop down. Inside the select dropdown, I have a "for" loop, looping through a List within ViewData. For each item, it creates an option in the select dropdown.

My issue is that for one or more of the items, the string value might be encompassed by "<>" characters.

However, when the page is rendered, that option is inserted into the select dropdown, but with a blank string for the value instead of "".

What do I have to do to go about rendering the "" in the dropdown's value attribute.

Here's my code:

    <select class="formtext" id="siteSelectDropdown" onchange="siteDropDownChange();" style="display:inline">
<%foreach (WebClientLib.Site site in ViewData["Sites"] as List<WebClientLib.Site>开发者_JAVA百科)
  {
      <option value="<%=site.Id %>"><%=site.Name%></option>
  }%>


Use <%: site.Id %> and <%: site.Name %> instead of the versions with =. Or, if you're in .NET 3.5 or earlier, instead do <%= Html.Encode(site.Id) %>; the former syntax is .NET 4 shorthand for the latter.

These HTML-encode the string before outputting it, so instead of e.g. <hello> you would get &lt;hello&gt;, which is the proper way to put < and > in HTML.

You should make a habit of ALWAYS doing this, and never using <%= stuff %>, since as mentioned by Anon's comment, the latter leaves you open to XSS and other HTML-injection attacks. Indeed, if you properly use HtmlStrings in your models and viewdata, you can avoid ever using the insecure version.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜