This should be a fairly simple question, all I want to do is use @Html.LabelFor within a razor view. One of my labels is different, it has an <a> tag in it. the problem is when I use LabelFor, it encodes the html as & lt;. I've tried a lot of different approaches to making this happen but none of them are working. Here's the code.
@Html.LabelFor(model => model.Question, new { @for = "Question" })
what should get outputted:
<label for="question"><a href=\"mailto:support@testdomain.com">support@testdomain.com</a></label>
what does get outputted:
<label for="question"><a href=\"mailto:support@testdomain.com">support@testdomain.com</a></label>
(my < have been replaced with & lt ; without the spaces, thus the code shows on the page instead of rendering as a link)
how can I make it output what it should?
note, model.Question is set to <a href="mailto:support@testdomain.com">support@testdomain.com</a>
答案 0 :(得分:1)
为什么您希望标签包含完整的HTML?我认为这是存储电子邮件地址的更好方法,在您的视图中,您可以这样做:
<a href="mailto:@Model.Email">@Model.Email</a>
获得预期结果。
修改强>
IMO通过对标签中的内容进行编码只会使您的工作变得更加复杂,因为标签并不意味着保留格式化的HTML或功能或类似的内容,而只是显示标题。用法示例:
型号代码:
[Display(Name = "Email address")]
public string EmailAddress { get; set; }
在视图中:
@Html.LabelFor(model => model.EmailAddress):
@Html.DisplayFor(model => model.EmailAddress)
<!-- OR (no label element just the label text)-->
@Html.DisplayNameFor(model => model.EmailAddress):
@Html.DisplayFor(model => model.EmailAddress)
然后可以以任何方式组合:
[Display(Name = "Send Email")]
public string EmailAddress { get; set; }
和
@Html.LabelFor(model => model.EmailAddress): <a href="mailto:@Model.EmailAddress">@Model.Email</a>
在运行时将是:
发送电子邮件: abc@server.com
答案 1 :(得分:0)
你正在与Razor系统作斗争,因为它默认编码。这就是使用Razor的美妙之处。包括Label
在内的许多标记类最终都会通过调用TagBuilderExtensions.ToMvcHtmlString
internal static class TagBuilderExtensions
{
internal static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode)
{
return new MvcHtmlString(tagBuilder.ToString(renderMode));
}
}
MvcHtmlString表示不应再次编码的HTML编码字符串。因此,您无法通过LabelFor
执行您要执行的操作。 Razor实际上是特别确保你不能。
但是因为你的麦芽酒:不管怎么说你真的不是标签:
@Html.Raw(Server.HtmlDecode(Model.MyField)