tags:

views:

40

answers:

2

Hello SO:

I am writing an MVC application with C#. In this one particular section, I have a conditional switch for the navigation to highlight the appropriate tab. Here is the code for that:

<script type="text/C#" runat="server">
    string oController;
    string oAction;
    const string current = "class=\"current_page\"";

    protected override void OnLoad(EventArgs e)
    {
        oController = ViewContext.RouteData.Values["controller"].ToString();
        oAction = ViewContext.RouteData.Values["action"].ToString();

        base.OnLoad(e);
    }
</script>

<div id="menu">
    <ul>
        <li <%= (oController.Equals("Home") ? current : "") %>><a href="/">Home</a></li>
        <li><a href="/CustomerManager/">Customer Manager</a></li>
        <!-- <%: oController.Equals("Home") %> -->
        <!-- <%: oAction %> -->
    </ul>
</div>

On this line (<li <%= (oController.Equals("Home") ? current : "") %>><a href="/">Home</a></li>) if I use the <%: %> ASP nugget instead of <%= %> (as is recommended, since the latter is being phased out soon), the generated text comes out as

<li class=&quot;current_page&quot;><a href="/">Home</a></li> 

Instead of

<li class="current_page"><a href="/">Home</a></li>

Any suggestions and/or reasons why this is happening? Thanks!

+4  A: 

Because <%: is intended to encode data such as user input. In your case, that is self-generated (trusted) html, so you don't want to encode it; <%= is the correct usage.

<%: is for things like <%:user.Name%>, which conveniently prevents issues for malicious text with xss etc in it.

Marc Gravell
Thank you for the clarification. I read on one of the ASP.NET MVC official tutorial that `<%=` is being removed after version 4. Do you know if this is true or not?
Anders
@Anders - I haven't heard that, but I would find it very unlikely. For starters, it would break too much code.
Marc Gravell
`<%=` is completely necessary sometimes. use `<%:` at all times unless you have a good reason not to (like yours). It isn't being phased out
BritishDeveloper
Thank you both for the clarity, I did think it was odd that they would try to phase out a tag.
Anders
A: 

You could just have the class be empty when the value is not Home. Clearly you are trying to omit it all together, but it would be a solution none the less.

const string current = "current_page";
<li class="<%: (oController.Equals("Home") ? current : "") %>"><a href="/">Home</a></li>
NickLarsen
The only issue with this is if the page is not selected there is no css class applied. An empty class tag seems inappropriate to me.
Anders