Razor view to DisplayFor DataType.Url that opens i

2019-06-23 08:17发布

How do I make links open in a new window with Razor and DisplayFor?

I have a property which is DataType.Url,

[DataType(DataType.Url)]
public string SiteUrl { get; set; }

Using @Html.DisplayFor this is converted into an a tag.

@Html.DisplayFor(model => item.SiteUrl)

However I need it to open in a new window. Setting new {target="_blank"} does not add the attribute for target

@Html.DisplayFor(model => item.SiteUrl, new {target="_blank" })

It is just this one page where I need the functionality of opening in a new window so using JavaScript seems a bit excessive.

How do I get the links to open in a new window?

1条回答
Root(大扎)
2楼-- · 2019-06-23 08:33

You could override the default template by adding a file in ~/Views/Shared/DisplayTemplates/Url.cshtml with the following contents:

<a href="@ViewData.Model" target="_blank">@ViewData.TemplateInfo.FormattedModelValue</a>
查看更多
登录 后发表回答