3

I have a class 'IncomeStatement' that is used as a ViewModel. This class has a property that generates some fairly complicated html like this:

public MvcHtmlString HtmlPeriods { get; set; }
.... 
StringBuilder htmlPeriods = new StringBuilder(100);
htmlPeriods.AppendFormat(
"<td><a href='/Forecast/IndexPeriod?Period={1}'>{0}</a></td>",
    inc.NetSales, per.Period.PeriodID);
....
HtmlPeriods = MvcHtmlString.Create(htmlPeriods.ToString())

Then in the Razor file I use the HtmlPeriods property, which works fine:

<th></th>@Model.HtmlPeriods<td></td>

But what if I want to use the Html.ActionLink(...) in my class to create
nice Razorlike links, something like this:

string forecastLink = 
Html.ActionLink("Edit Forecast", "/Forecast/IndexEdit?PeriodID=2005Q1");

How would I do that?

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
Dick de Reus
  • 779
  • 1
  • 7
  • 15

2 Answers2

4

You can use the HtmlHelper class to do this. I think you will want the GenerateLink method.

Example:

string link = HtmlHelper.GenerateLink(HttpContext.Current.Request.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Default", "Index", "Home", null, null);
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
0

In your situation it would be more correct to define HTML helpers instead of using properties and methods on your models. For example:

using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class HtmlExtensions
{
    public static MvcHtmlString HtmlPeriods(this HtmlHelper<SomeViewModel> html)
    {
        // here you can use html.ActionLink in order
        // to generate the desired markup

        // you also have access to the view model here:
        SomeViewModel model = html.ViewData.Model;

        ... 
    }
}

and then in your view:

@Html.HtmlPeriods()
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Darin - I agree that a helper would be better in most cases. However in this case I need to process sequential year records of a database table (vertical ordering) and present them in a horizontal fashion. My first approach was to have a 'foreach year' loop in a helper for each field in the table - not very eficient. – Dick de Reus Aug 03 '11 at 11:39
  • Now I do more html work in the ViewModel (agains the rules - I now) looping through the year records once, adding to StringBuilders to be used as html rows in the razor page. So one foreach instead of about 30. – Dick de Reus Aug 03 '11 at 11:46
  • @Dick de Reus, I am not sure I understand what you are taking about without showing some code. Every code could be refactored and optimized in HTML helpers. What you describe is better suited to a helper IMHO. – Darin Dimitrov Aug 03 '11 at 11:49