【问题标题】:DisplayName metadata does not show up on viewDisplayName 元数据未显示在视图中
【发布时间】:2010-12-16 02:08:49
【问题描述】:

考虑到以下模型,我将如何在视图上显示正确的 DsiplayName。

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Project.Models.RegisterViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <% using (Html.BeginForm())
       {%>
    <table>
        <tr>
            <td class="label">
                <%: Html.LabelFor(model => model.User.UserPrimaryEmail)%>
            </td>
            <td class="field">
                <%: Html.TextBoxFor(model => model.User.UserPrimaryEmail)%>
            </td>
            <td class="field-error">
                <div class="field-error-msg">
                    <%: Html.ValidationMessageFor(model => model.User.UserPrimaryEmail)%>
                </div>
            </td>
        </tr>
 </table>
</asp:Content>
public class RegisterViewModel
{
    public User User { get; set; }
}


[MetadataType(typeof(UserMetaData))]
public partial class User : UserBase
{
 //Inherits from Generated Class UserBase
 //to set default values here for the constructor

    // Not used except as a source of metadata
    public class UserMetaData
    {

        [Required]
        [DisplayName("Email Login")]
        [DataType(DataType.EmailAddress)]
        [Email(ErrorMessage = "Invalid Email")]
        public string UserPrimaryEmail { get; set; }


    }

}

表单不显示“Email Login”而是“UserPrimaryEmail”

【问题讨论】:

标签: asp.net-mvc-2 attributes metadata data-annotations


【解决方案1】:

您的视图被强类型化为 Project.Models.RegisterViewModel,但是您正在将数据注释添加到用户对象。

通常你会:

public class RegisterViewModel
{
    [Required]
    [DisplayName("Email Login")]
    [DataType(DataType.EmailAddress)]
    [Email(ErrorMessage = "Invalid Email")]
    public String Email { get; set; }

    .....
    other properties
}

【讨论】:

  • 除了丢弃我的“用户”对象之外,没有其他方法可以做到这一点。
  • 不行,没有别的办法。这确实是 ViewModel 应有的样子。一组与视图中的数据匹配的属性,充当实体和 UI 之间的抽象级别。我建议使用 AutoMapper 之类的工具来简化此操作。
猜你喜欢
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多