How to avoid Adding runat=“server” destroying my s

2019-07-04 04:11发布

问题:

Adding runat="server" is not rendering my server tags <%...%>


I have a masterpage with a few <li> for menu and since I have to set class=selected for the current page, I am using a little server tag to find the url and assign the particular class.

I have total of 10 <li> and not all menu is available to all types of user, I need to toggle few of the <li> if the user is not admin, so I have runat="server" added to them so I can set their visible=false through c#

Here is how it is at a glance:

<li runat="server" id="liBlog" class='<%= Request.Url.AbsoluteUri.EndsWith("/Blog") ? "selected" : "" %>'><a href="/Blog">Group Blog</a></li>
<li runat="server" id="liPoll" class='<%= Request.Url.AbsoluteUri.EndsWith("/Poll") ? "selected" : "" %>'><a href="/Poll">Poll</a></li>
<li id="liInvite" class='<%= Request.Url.AbsoluteUri.EndsWith("/Invite") ? "selected" : "" %>'><a href="/Invite">Invite</a></li>
<li id="liFavourite" class='<%= Request.Url.AbsoluteUri.Contains("/Favourite") ? "selected" : "" %>'><a href="/Favourite">My Favourites</a></li>

The <li> without runat="server" works fine, when on correct page the source code shows class="selected" or class="" as appropriate, the other <li> used to work fine too, until I decided to add the runat="server".

Once I added that runat="server", the whole block of class="" is being sent out to the html page, its not processing the server tags at all! I right click on the html and look at the source, it's being rendered as:

<li id="ctl00_ctl00_ContentPlaceHolder1_liBlog" class="&lt;%= Request.Url.AbsoluteUri.EndsWith(&quot;/Blog&quot;) ? &quot;selected&quot; : &quot;&quot; %&gt;"><a href="/Blog">Group Blog</a></li>

It's pouring out my server tags into the source code!

Why is this behaviour seen? How can I avoid it?

I looked up a lot of similar threads in here and there was nearly nothing in google, so made this, I dont think this is a duplicate question.

回答1:

You can't use the <%= %> syntax inside the properties of tags that have the runat="server" attribute on them.

You either need to:

  • Set the properties via your code-behind
  • Create an Expression Builder (and part 2 and part 3) and use the <%$ %> syntax (note: these are links to stuff I wrote on my blog, so, beware the self link =)


回答2:

for your requirement you can also use ASP.NET menu and XmlSiteMap to do the same thing.