1

I have a razor view where I'm currently using code that looks something like this:

@if(Model.IsLink)
{
    <a href="...">
}

Some text that needs to appear

@if(Model.IsLink)
{
    </a>
}    

This works but the code doesn't feel clean. Is there a better/more accepted way of accomplishing this pattern?

tereško
  • 58,060
  • 25
  • 98
  • 150
Mykroft
  • 13,077
  • 13
  • 44
  • 72

3 Answers3

2

You could create a custom HtmlHelper method. See the reference on how to do that here: http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs

Your method could take the "IsLink" boolean as a parameter, and use it to either output an anchor or plain text. Here's a sample of what that might look like:

namespace MvcApplication1.Helpers
{
     public static class LabelExtensions
     {
          public static string LinkableText(this HtmlHelper helper, bool isLink, string text, string url = null)
          {
               return isLink ? string.Format("<a href='{0}'>{1}</a>", url, text) : text;

          }
     }
}
htxryan
  • 2,871
  • 2
  • 21
  • 21
2

Here is a simple method I think is a little cleaner.

Set the text to a variable at the top of the view:

@{
   var someText = "Some text that must appear";
 }

Then output conditionally:

@if (Model.IsLink)
{
    <a href='#'>@someText </a>
}
else
{
    @someText
}

The multi-line if statement above avoids doing string construction with HTML, but if you want to condense the syntax down to one line you can do this.

@Html.Raw(Model.IsLink?String.Format("<a href='#'>{0}</a>",someText):someText)
PeaceFrog
  • 727
  • 1
  • 6
  • 14
1

In HTML 5 it is valid to have markup like this if you do not have a link

<a>some text</a>

and markup like this if you do

<a href="http://example.com">some text</a>

And as of razor v2 your null conditional attributes take care of the href, so your code can be like this.

<a href="@link">some text</a>

If @link is null the href attribute will be omitted.

Community
  • 1
  • 1
Myster
  • 17,704
  • 13
  • 64
  • 93