Reputation: 6301
I'm working on an app using ASP.NET MVC. I need to be able to sometimes display a link. Other times, I just need to use text. In an attempt to accomplish this, I've written the following in my view:
@{
var showLink = !String.IsNullOrWhiteSpace(item["id"].ToString());
if (showLink) {
Html.Raw("<a href=\"#\">");
}
Html.Raw(item["name"]);
if (showLink) {
Html.Raw("</a>");
}
}
Unfortunately, this isn't working. The name does not render. However, if I put @item["name"]
just above the @{
the name appears just fine. What am I doing wrong?
Upvotes: 3
Views: 514
Reputation: 25221
You're calling Html.Raw(item["name"])
inside a code block (@{ ... }
) - code blocks are run as normal C#; their result is not rendered to the response like inline Razor. Because of that, the string that is returned by Html.Raw
is just being discarded.
You want:
@{
var showLink = !String.IsNullOrWhiteSpace(item["id"].ToString());
}
@if (showLink)
{
@Html.Raw("<a href=\"#\">");
}
@Html.Raw(item["name"]);
@if (showLink)
{
@Html.Raw("</a>");
}
Upvotes: 3