R – Should I be able to understand this ContentPlaceHolder behavior

asp.netasp.net-mvccontentplaceholder

My goal is to be able to define a class for the element in a child page. On my master page I have the following:

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

The AttributePlaceHolder derives from ContentPlaceHolder, and just strips out any linebreaks and extra spaces from its content. The problem I will describe also occurs when changing the AttributePlaceHolder into a normal ContentPlaceHolder .

Now the above stated piece of code doesn't work, and will end up in the following error:

Cannot find ContentPlaceHolder
'BodyCssClass' in the master page
'/Views/Shared/Site.Master', verify
content control's ContentPlaceHolderID
attribute in the content page

When changing the above line of code into:

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

It does work (note the added <% %>).

It does the trick, just wondering if I'm missing something here.

Just for the extra info, in my child pages I can write:

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

or even:

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

another-class
</asp:Content>

and it will be nicely printed out as:

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

Edit
As pointed out by Johan the following also works:

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

Changes the double quotation marks into single ones.

But than my html would also show up with single quotation marks. Call me crazy, but that just hurts me…

I guess it has to do with the ASP.NET parsing engine, in that case should we call it a bug, or a "feature"?

Best Answer

You can also achieve the double quotation marks in the output without using the server tags by reversing the quotes setup:

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

The runat and ID attributes of the place holder are single quoted. As to why the server tag makes the original code work, only the demons inside the parsing engine know that...