Search code examples
asp.netasp.net-mvc-3razorhtml-rendering

MVC3 ascx vs razor page rendering issue


I have an aspx web page that renders correctly. When converted to razor, it does not. Here is a simplified example (stripped of all extraneous stuff).

aspx:

   <asp:Content ID="indexContent" ContentPlaceHolderID="ToolContent" runat="server">
      <% string test = "<div><b>Tag Test</b></div>"; %>
      <h2><%= test %></h2>
   </asp:Content>

razor:

   @section ToolContent {
      @{ string test = "<div><b>Tag Test</b></div>"; }
      <h2>@test</h2>
   }

The aspx renders as expected. The razor just displays the content of "test" (<div><b>Tag Test</b></div>) in the header tag.

I assume that my understanding of razor is flawed. If someone could enlighten me and/or show me a solution/work around, I would greatly appreciate it.


Solution

  • When you write @test, Razor automatically escapes it.

    To prevent it from being escaped, write @Html.Raw(test).