Domanda

I'm wondering if anyone can confirm this behavior or if I've done something wrong.

Normally when you specify the DataType(DataType.MultilineText) attribute, and do something like @Html.DisplayFor(m => m.Body) MVC will use the MultilineText.cshtml in the DisplayTemplates folder. That does not seem to work when the DataType attribute is applied to an overriden property as in the code below. Now if I move the attribute to the property in the abstract class it MVC does use the MultilineText.cshtml display template.

public abstract class PostBase
{
    [Required]
    public virtual string Body { get; set; }
}

public class MessagePost : PostBase
{
    [StringLength(500), DataType(DataType.MultilineText)]
    public override string Body
    {
        get { return base.Body; }
        set { base.Body = value; }
    }
}
È stato utile?

Soluzione

What's the Model in declared in your view? The abstract or child?

It uses reflection to read the attribute based on the model declared so:

@model PostBase

@Html.DisplayFor(m => m.Body)

Will work differently to

@model MessagePost

@Html.DisplayFor(m => m.Body)

the first of these will apply the [Required] only. It's bound to a PostBase model (doesn't know or care what the child class), so when it reflects the PostBase class; this only has [Required] on that property. So it never looks for the MultilineText.cshtml, why would it? It's not got MultilineText on it.

The second one will apply [StringLength(500), DataType(DataType.MultilineText)] and [Required]. The attributes are combined for inherited classes so when it reflects the class it'll see both attributes.

This view should use the template as required. I'm guessing this doesn't work for you though as I'm presuming the inheritance is there for a reason?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top