I have created a Model class lets say Products. I want to have a property ‘ItemName’ return an HTML link everytime it is put into an HTML document. For example:
public class Product
{
int ItemID {get; private set;}
[HtmlReturn(Link=Html.ActionLink("Products", "Details", new {id=ItemID})] // <-- Something like this
int ItemName {get; private set;}
int Price {get; private set;}
}
Now anytime the ItemName is used in an HTML document, the value is output as a link to the Product/Details page for that item. This would allow output of the ItemName in many different locations with the assurance that it will always be a link anywhere it is referenced on a web site.
You could implement a separate member variable with a get-only accessor in your
Productclass calledItemAsLink, that returns the HTML formatted link value. That is what I usually do when running into a situation like this. It has the disadvantage of moving some of the UI/view/display code into the model, but as you say, it helps with code reuse.The way you are suggesting does the same thing (moves code that should be in the view into the model). In my opinion, it also would be confusing, because
ItemNamewould have a different value depending on how it was called. That violates the expectation thatItemNameis always the same regardless of how it is used.