0
votes

When creating a new class model, if you apply the Data Annotation type "[DataType(DataType.EmailAddress)]", or "[EmailAddress]", I get the raw output being displayed in my HTML.

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

And in my Razor HTML, I have:

// 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>

For instance, say I have 3 records in my database "Product". The Razor HTML code loops through the database to display each record.

By applying the Data Annotation "[DataType(DataType.EmailAddres)]" or "[EmailAddress]", it seems to cause some weird effect of converting it into a literal string, meaning that instead of displaying the data from the database in the correct way, which is 'Published by: [email protected]', it instead outputs it as a single liner string '[email protected] > [email protected] > [email protected] >' in the View.

Does anyone have any idea as to why this is the case?

For additional information, I'm using ASP.NET Core version 3.0 MVC, though if I recall, this was also present in version 2.1.

1
You probably have wrong return characters at end of line. Windows uses 0x0D and then 0x0A. Your email has only 0x0D which probably means it came from Linux. - jdweng
DisplayFor returns an actual HTML anchor tag (i.e. link) with the email for an email type. That's invalid inside of an HTML attribute, causing the HTML to break. If all you want is the email address string itself, just print it directly (i.e. @item.Publisher), rather than using Html.DisplayFor. - Chris Pratt
Ok, that definitely underlines the issue. Didn't know that by adding that Data Annotation [EmailAddress] would cause it to generate an email address string. I initially thought it would register that database attribute as an email string on the database side, and not throughout the entire program. - QuantumPhysics

1 Answers

2
votes

If you check the html source in your browser, you would find the code snippet @Html.DisplayFor(modelItem => item.Publisher) would render the field (EmailAddress) as a hyperlink instead of the simple text, like below.

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

Which cause the html messed up. You can try to modify the code like below.

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

    </tr>
    }
</tbody>

Test result

enter image description here