Wondering why DisplayName attribute is ignored in LabelFor on an overridden property

大兔子大兔子 提交于 2019-12-01 02:17:42

Model binding and metadata using the strongly-typed helpers looks at the declared, rather than the runtime, type of the model. I consider this a bug, but apparently the MVC team disagrees with me, as my Connect issue on this was closed as "By Design."

I ran into this problem using [DisplayName("Profile Name")] and instead used [Display(Name = "Profile Name")] which fixed the problem in my case. I'm not sure if this would be useful.

The former is from System.ComponentModel whilst the latter is from System.ComponentModel.DataAnnotations.

I had the same issue when I had a partial view strongly-typed to an interface. The interface defined a DisplayName and the class that implemented the interface tried to override it. The only way I found to get it to respect the override was to type to the implementing class. I had to either change the view's model type or cast. Unfortunately, that completely negates the benefits of using the interface as the model type. I am guessing that I will end up with some level of duplicated view markup for each implementing class while not casting within the strongly-typed "helpers".

In the remote chance that this type of workaround is even remotely helpful (not getting my hopes up), here is an example. There are certainly ways of working handling into this for all possible implementing classes that try to override a name, but it is definitely more hassle than it should be.

public interface IAddressModel {
    ...
    [DisplayName("Province")]
    public string Province { get; set; }
    ...
}
public class UsAddressModel : IAddressModel {
    ...
    [DisplayName("State")]
    public string Province { get; set; }
    ...
}

<%= Html.LabelFor(m => m.State) %> <!--"Province"-->
<%= Html.LabelFor(m => (m as UsAddressModel).State) %> <!--"State"-->
Nicholas Bechstein

Ok, I seem to have found a workaround if you don't use the Required tag with it! just use a regular expression or length attribute to determine if there is a valid entry. Hope this helps, though it's a little late.

[RegularExpression(@"^[1-9][0-9][0-9]$")]   //validates that there is at least 1 in the quantity and no more than 999
[DisplayName("Quantity:")]
public string quantity { get; set; }

Still works.

In my case I was forgotten to make it a property by using getters and setters. Instead of

public string CompanyName;

I should have used

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