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.ActionL开发者_运维技巧ink("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 Product
class called ItemAsLink
, 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 ItemName
would have a different value depending on how it was called. That violates the expectation that ItemName
is always the same regardless of how it is used.
I would suggest adding it as an extension method to your class to keep your view code separate from your model, like so:
public static class ProductHelper
{
public static MvcHtmlString ProductLink(this HtmlHelper html, Product product)
{
return html.ActionLink(product.ItemName, "Details", "Product", new { id = product.Id });
}
}
Then use in your view like this:
@Html.ProductLink(product)
Which would generate something like:
<a href="/products/details/1">Product 1's item name</a>
精彩评论