Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Razor - Can I put a link in a ternary operator?

I have a ternary operator in my MVC4 View:

@(modelrecord.Website == null ? "" : modelrecord.Website.Replace("http://","") )

This works, but I want to make the website record a hyperlink. Is this possible?

Note: I'm replacing the "http://" prefix because it's ugly.

If I put in the actual string with Html.Raw, the angle brackets are escaped, and I still don't get a link.

like image 798
northben Avatar asked Jan 30 '26 04:01

northben


1 Answers

You should probably be using DataAnnotations and the @Html.DispayFor helper.

public class ModelRecord
{
    [DataType(DataType.EmailAddress)]
    public String EmailAddress { get; set; }

    [DataType(DataType.Url)]
    public String Website { get; set; }
}

Then:

email me at @Html.DisplayFor(x => x.EmailAddress)
or visit me online at @Html.DisplayFor(x => x.Website)

The DataTypeAttribute handles things like urls, emails, etc. and formats them depending.

If you want to customize all Urls, you can create a display template for it:

~/Views/Shared/DisplayTemplates/Url.cshtml

@model String
@if (!String.IsNullOrEmpty(Model))
{
    <a href="@Model">@Model.Replace("http://", "")</a>
}
else
{
    @:Default text when url is empty.
}

DisplayTemplates (like EditorTemplates) is a convention-based path that MVC uses. because of this, you can place the template in the Shared directory to apply this change site-wide, or you can place the folder within one of the controller folders to only have it apply to that controller (e.g. ~/Views/Home/Displaytemplates/Url.cshtml). Also, Url is one of the pre-defined templates included for use with DisplayType, along with the following:

  • Url
  • EmailAddress
  • HiddenInput
  • Html
  • Text
like image 122
Brad Christie Avatar answered Feb 01 '26 19:02

Brad Christie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!