繁体   English   中英

ASP.NET Core MVC 3.0 - 'EmailAddress' 数据注释导致 HTML 输出故障

[英]ASP.NET Core MVC 3.0 - 'EmailAddress' data annotation causing HTML output glitch

创建新的类模型时,如果应用数据注释类型“[DataType(DataType.EmailAddress)]”或“[EmailAddress]”,我会在 HTML 中显示原始输出。

// In ~/Models/Product.cs
// using System.ComponentModel.DataAnnotations;
public class Product
{
    [DataType(DataType.EmailAddres)]
    public string Publisher { get; set; }
}

在我的 Razor HTML 中,我有:

// In ~/Views/Products/Index.cshtml
<table class="table">
    <tbody>
        @foreach (var item in Model)
        {
            // gets displayed as a literal string format instead of data from database
            <tr title="Published by: @Html.DisplayFor(modelItem => item.Publisher)"></tr>
        }
    </tbody>
</table>

例如,假设我的数据库“产品”中有 3 条记录。 Razor HTML 代码循环遍历数据库以显示每条记录。

通过应用数据注释“[DataType(DataType.EmailAddres)]”或“[EmailAddress]”,它似乎会导致一些奇怪的将其转换为文字字符串的效果,这意味着不是以正确的方式显示数据库中的数据方式,即 ' Published by: john.smith@test.com ',而是将其输出为单行字符串'john.smith@test.com > john.smith@test.com > john.smith@test.com >'在视图中。

有没有人知道为什么会这样?

有关其他信息,我使用的是 ASP.NET Core 3.0 版 MVC,但如果我记得,这也出现在 2.1 版中。

如果您在浏览器中检查 html 源代码,您会发现代码片段@Html.DisplayFor(modelItem => item.Publisher)会将字段 (EmailAddress) 呈现为超链接而不是简单的文本,如下所示。

<a href="mailto:john.smith@test.com">john.smith@test.com</a>

这导致 html 搞砸了。 您可以尝试修改如下代码。

<tbody>
    @foreach (var item in Model)
    {
    <tr title="Published by: @item.Publisher">
        <td>
            @Html.DisplayFor(modelItem => item.Publisher)
        </td>

    </tr>
    }
</tbody>

测试结果

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM