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

问题描述 投票:0回答:1

[创建新的类模型时,如果应用数据注释类型“ [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]”,似乎会产生一些将其转换为文字字符串的怪异效果,这意味着与其在数据库中显示数据库中的数据正确的方式是“ 发布者:[email protected]”,而是将其输出为单个衬线字符串'[email protected]> [email protected] > [email protected]>'

有人对为什么会这样有任何想法吗?

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

c# html razor asp.net-core-mvc data-annotations
1个回答
2
投票

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

<a href="mailto:[email protected]">[email protected]</a>

导致html混乱的原因。您可以尝试如下修改代码。

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

    </tr>
    }
</tbody>

测试结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.