ASP.NET MVC DisplayAttribute and interfaces

这一生的挚爱 提交于 2019-12-11 21:00:58

问题


I have some interface and classes

public inteface IRole
{
  int Id { get; }
  string Name { get; set; }
}

public class Role : IRole
{
  public int Id { get; }
  [Display("Role Name")]
  public string Name { get; set; }
}

public class Member 
{
  [Display("Login")]
  public string Login { get; set; }
  [Display("Password")]
  public string Password { get; set; }
  public IRole Role { get; set; }
}

on View I try to use, View is strongly type of Member

on this line displays correct message from DisplayAttribute

<%= Html.LabelFor(m => m.Login) %>

on this line it does not display correct label from DisplayAttribute

<%= Html.LabelFor(m => m.Role.Name) %>

How can I fix this to have correct labels in such architecture?

Thanks

P.S. I know about adding DisplayAttribute to the interface field and all will work, but maybe there are different solution.


回答1:


Everything is working as designed here.

You already know your answer. If you display a form for IRole you must also have the attributes on IRole.


In order to have the correct labels you'd have to implement your own TypeDescriptors or ModelMetadataProvider in order to "smush" together the metadata for an interface into any concrete classes that implement them.

This will become really complex real fast.

Why can't you just add the attribute to the IRole interface?



来源:https://stackoverflow.com/questions/2652811/asp-net-mvc-displayattribute-and-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!