2

I have a simple view model

public string LinkName { get; set; }

[Display(Name = "Url")]
[DataType(DataType.Url)]
public string Link
{
  get
  {
     return string.Format(/*some link building logic*/);
  }
}

But when I try to display it in view with

@Html.DisplayFor(m => m.Link)

I'm getting whole Url displayed and I'd like to just display LinkName i.e something like this

<a href="http://...">http://...</a>

but I'd like to have it like this:

<a href="http://...">LinkName</a>
tereško
  • 58,060
  • 25
  • 98
  • 150
Icen
  • 441
  • 6
  • 14
  • Do you mean `@Html.DisplayFor(m => m.LinkName)`? What is the value of `Link` and `LinkName`? –  Sep 12 '15 at 07:55

1 Answers1

3

There is no way for MVC to pull in a value from another property when you use DisplayFor so you have 2 options. First you can build it manually:

<a href="@Model.Url">@Model.LinkName</a>

The next option would be to make your own class and custom display template. For example:

public class NamedUrl
{
    public string Name { get; set; }
    public string Url { get; set; }
}

Your new model:

public class YourModel
{
    public NamedUrl MyUrl { get; set; }
}

The display template (put it in Views/Shared/DisplayTemplates/NamedUrl.cshtml):

@model YourAssembly.NamedUrl
<a href="@Model.Url">@Model.LinkName</a>

And now in your view you can use:

@Html.DisplayFor(m => m.MyUrl)
DavidG
  • 113,891
  • 12
  • 217
  • 223