开发者

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

开发者 https://www.devze.com 2023-02-19 20:03 出处:网络
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 th

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号