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 开发者_如何学JAVAMyModel
{
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="<%: MyModel.MyString %>" rel="<%: 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:
精彩评论