I have a model with some inheritance worked into it, but here’s the thing, I want to apply different HTML attributes depending on which type it is. So my thought was to create a property, I’ll call it DisplayString, which is used as the first argument to String.Format. DisplayString is used to allow me to do something like this:
Classes:
public class Reaction
{
public string ReactionString { get; set; }
public string DisplayString { get; set; }
public Reaction(string reactionString)
{
ReactionString = reactionString;
DisplayString = "It was {0}!"
}
public Reaction(string reactionString, string displayString)
{
ReactionString = reactionString;
DisplayString = displayString;
}
}
public class GoodReaction : Reaction
{
public GoodReaction()
{
base("awesome");
}
}
public class BadReaction : Reaction
{
public GoodReaction()
{
base("horrible");
}
}
public class AverageReaction : Reaction
{
public GoodReaction()
{
base("alright", "It kinda was {0}...");
}
}
View:
@model Reaction
@String.Format(Model.DisplayString, "<strong>" + Model.ReactionString + "</strong>");
So basically every subclass has a string I want to display, but I have varying text AND varying markup. Of course doing it this way just results with the strong tags rendered as text. So what are my options? Feel free to ask any questions needed to clarify, hopefully I got my question across properly. Thanks!
EDIT:
So I wrapped it in Html.Raw() and that did the trick, although I’m sure there is something bad about doing that and I should probably encode each piece, then add tags, then raw, or something, but for my purposes it works.
I would create a display template for each concrete class, and MVC will be smart enough to pick the right one.
E.g when you call
@Html.DisplayFor(model => model.Reaction), whereReactionis declared as the base class, MVC will work out what type it is, then look for a template matching that type, if it doesn’t find it, it will look for a template of the base type, then finally fallback to the default template. I do this a lot in my application.Sounds like you should also make the
Reactionclass abstract, and the ctor’s protected.