0

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.

2
  • You could return ItemName as a custom type and use a template to render it as a HyperLink? This would help keep your view (the HTML) seperate from your models and view models. Commented May 4, 2011 at 15:25
  • The idea was to avoid coding in every template where it may be used. I was hoping there was an attribute that would return a value to any view when accessed as a strongly typed Model. Commented May 4, 2011 at 15:36

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

Thank, although the idea was to have some attribute so that when building the View, it wasn't necessary to specify a link when the value was referenced. This would help make linking to an item consitant throughout the website.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.