简体   繁体   中英

ASP.NET MVC 3.0 Conditionally writing inline text within a tag

I have this tag in my menu

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

and I was wanting to insert a class="selected" if the current controller was the HomeController. So I modified the tag to look like this.

<li><a href="/" @if (ViewContext.Controller.ToString().EndsWith("HomeController")) { Response.Write("class=\"selected\""); }>Home</a></li>

Now, I see the class= &quot; selected &quot; appear at the top of the page and the rest of the markup is messed up. I just wanted to have the tag look like this

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

If the current controller is the HomeController.

Any ideas what I did wrong?

Thanks!

Try

<a href="/" @if (ViewContext.Controller.ToString().EndsWith("HomeController")) { <text>class="selected"</text> }>Home</a>

Razor encodes everything by default, if you use the special tag <text> it renders the content as is.

Here is a quick reference guide on Razor syntax: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM