【问题标题】:Should I be able to understand this ContentPlaceHolder behavior?我应该能够理解这种 ContentPlaceHolder 行为吗?
【发布时间】:2009-06-11 07:46:14
【问题描述】:

我的目标是能够为子页面中的元素定义一个类。在我的母版页上,我有以下内容:

<body class="<myown:AttributePlaceHolder runat="server" ID="BodyCssClass"/>">

AttributePlaceHolder 派生自 ContentPlaceHolder,只是从其内容中去除任何换行符和多余的空格。我将描述的问题也发生在将AttributePlaceHolder 更改为普通ContentPlaceHolder 时。

现在上面这段代码不起作用,最终会出现以下错误:

找不到 ContentPlaceHolder 母版页中的“BodyCssClass” '/Views/Shared/Site.Master',验证 内容控件的 ContentPlaceHolderID 内容页面中的属性

当把上面这行代码改成:

<body class="<% %><myown:AttributePlaceHolder runat="server" ID="BodyCssClass"/>">

它确实有效(注意添加的&lt;% %&gt;)。

它可以解决问题,只是想知道我是否在这里遗漏了什么。

为了额外的信息,我可以在我的子页面中写:

<asp:Content ContentPlaceHolderID="BodyCssClass" runat="server">profile-edit someotherclass another-class</asp:Content>

甚至:

    <asp:Content ContentPlaceHolderID="BodyCssClass" runat="server">profile-edit
someotherclass

another-class
</asp:Content>

它会很好地打印出来:

<body class="profile-edit someotherclass another-class">

编辑
正如 Johan 所指出的,以下方法也有效:

<body class='<myown:AttributePlaceHolder runat="server" ID="BodyCssClass"/>'>

把双引号变成单引号。

但我的 html 也会出现单引号。说我疯了,但这只会伤害我......

我猜这与 ASP.NET 解析引擎有关,在这种情况下,我们应该称其为 bug 还是“功能”?

【问题讨论】:

  • 你不能改变单引号的位置吗?
  • 这确实应该有效。那是你去“dohhh”的那些事情之一。无论如何仍然不能解释这种行为。
  • 不,这确实没有任何意义,但如果你仔细想想;什么时候在另一对双引号中的双引号在没有转义或将它们更改为单引号的情况下起作用?所以在某种程度上它是有道理的,但在另一种方式它没有..
  • 但这可以解释添加 以使其工作的行为...

标签: asp.net asp.net-mvc contentplaceholder


【解决方案1】:

您还可以通过反转引号设置来实现输出中的双引号而不使用服务器标签:

&lt;body class="&lt;myown:AttributePlaceHolder runat='server' ID='BodyCssClass'/&gt;"&gt;

占位符的 runat 和 ID 属性是单引号的。至于为什么server标签让原代码工作,只有解析引擎里面的恶魔才知道……

【讨论】:

    【解决方案2】:

    试试这样的:

    <body class='<asp:ContentPlaceHolder id="PlaceHolderTitleAreaClass" runat="server">ms-areaseparator</asp:ContentPlaceHolder>' ... >
    

    【讨论】:

      【解决方案3】:

      你有没有想过这个?

      在您的 aspx 页面中已将 body 标记设置为服务器对象

      <body runat="server" id="HtmlBody">
      

      然后在你后面的代码中你可以设置任何你喜欢的属性

      HtmlBody.Attributes.Add("class", "your-css-class-name");
      

      这会产生以下标记

      <body id="ctl00_HtmlBody" class="your-css-class-name">
      

      【讨论】:

      • 虽然我没有在文中说明,但我确实将它标记为MVC。所以我没有后面的代码,也不想在控制器中设置类名。类名应该在视图中设置。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多