简体   繁体   中英

ASP.NET MVC html writer bug?

It's probably a bug. Steps to reproduce:

(1) Create a ASP.NET MVC 3 project (ASPX view engine)

(2) Go to the Models folder and create a new simple model

namespace MvcApp.Models
{
    public class MyModel
    {
        public static string MyString = "foo";        
    }
}

(3) Modify the web.config file, add the namespace of the models, so that you can use models in your views.

      ....
      </controls>
      <namespaces>
        <add namespace="MvcApp.Models" />
      </namespaces>
    </pages>
  </system.web>

(4) Go to /Shared/Site.Master , modify the <head> section.

<head runat="server"> 
    <title><%: MyModel.MyString %><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="<%: MyModel.MyString %>" rel="<%: MyModel.MyString %>" />
    <script src="<%: MyModel.MyString %>" />
</head>

Note runat="server" attribute of head.

(5) Run it, and see the source code of the page. I think you will get(unnecessary spaces are removed):

<head id="Head1">
   <title>foo Index</title>
   <link href="&lt;%: MyModel.MyString %>" rel="&lt;%: MyModel.MyString %>" />
   <script src="foo" />
</head>

Something interesting:

a. All attributes of link tag aren't evaluated correctly. it looks like being encoded? While the same expressions in title and script are correct.

b. Change the 3rd line to this:

<link href="<%: MyModel.MyString %>" rel="<%: string.Format("{0}", "foo") %>" />

OR

<link href="<%: MyModel.MyString %>" rel="<%: "foo" %>" />

You will get everything correct(even href is correct.).

c. head without runat="server" is always correct.

I think it's a bug when rendering views to html texts. It's really a nightmare to check the source code and try to find the bug. Can anyone tell me the reason?

The simple reason is that ASP.NET Server control never convert <% %> tags. Since your Head contains runat="server", then ASP.NET Web Form Engine takes some interenal decision for every child control whether to make it a web server control or not.

Put this

<head id="Head1" runat="server"> 
<title><%: MyModel.MyString %><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link id="link1" href="<%: MyModel.MyString %>" rel="<%: MyModel.MyString %>" />
<link id="link2" href="<%: MyModel.MyString %>" rel="<%: string.Format("{0}", "foo") %>" /><%sa %>
<script src="<%: MyModel.MyString %>" />
</head>

<script src="<%: MyModel.MyString %>" />

Now carefully check Show Complete Compilation Source:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM