3

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?

1 Answer 1

3

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>");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.