Reputation: 5588
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.
Upvotes: 3
Views: 1273
Reputation: 101604
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:
Upvotes: 3