How to use multiple DisplayName attribute using Entity Framework and ASP.Net Mvc 2

筅森魡賤 提交于 2019-12-11 11:15:42

问题


Depending on where I use my Class, I want to be able to show a different DisplayName.
I have the following class:

[MetadataType(typeof(PortalMetaData))]
[System.Web.Mvc.Bind(Exclude = "PortalId")] 
public partial class Portal
{
    public Portal()
    {
      this.Created = DateTime.Now;
    }
}
public class PortalMetaData
{
    [Required(ErrorMessage = "Portal name is required")]
    [StringLength(50, ErrorMessage = "Portal name must be under 50 characters")]
    public object PortalName { get; set; }

    [Required(ErrorMessage = "Description is required")]
    public object Description { get; set; }
}

I have a corresponding Table in the database Portal

I use the Portal table with a PortalController for the Site Admin to update the records in the Portal Table.

I want another user with a different Role (AsstAdmin) to be able to update this table as well.
To facilitate that I am thinking of creating a separate partial class that somehow links back to the Portal Model. This would allow me to display limited Fields for update by the AsstAdmin and I can display a different name for the Field as well.

How can I accomplish this task? If I add the following class which inherits from Portal than I get an exception:

Unable to cast object of type 'Project1.Mvc.Models.Portal' to type 'Prpject1.Mvc.Models.Site'.

[MetadataType(typeof(SiteMetaData))]
public class Site : Portal
{
    public Site() {  }        
}

public class SiteMetaData
{
   [Required(DisplayName = "Site Description")]
   public object Description { get; set; }
}

回答1:


You could create two different view models that have the only the fields each type of user can see. You will need a service to do the appropriate mapping back to the Portal entity when saving.



来源:https://stackoverflow.com/questions/2489328/how-to-use-multiple-displayname-attribute-using-entity-framework-and-asp-net-mvc

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